【发布时间】:2014-10-27 23:40:36
【问题描述】:
我正在使用以下代码将 JTextArea 添加到我的 JPanel:
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
this.add(commentTextArea);
commentTextArea.setBounds(0, 0, 100, 100);
//commentTextArea.setLocation(0, 0);
每当我使用 setLocation(0,0) 时,JTextArea 永远不会移动。它始终位于屏幕的顶部中间,而不是 (0,0)。 setBounds(0,0,100,100) 也是如此,但高度和宽度是这样设置的,而不是位置。这是为什么呢?
完整代码
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
JTextArea commentTextArea = new JTextArea(10, 10);
public Canvas() {
this.setOpaque(true);
}
public void addTextBox() {
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
commentTextArea.setLocation(0, 0);
this.add(commentTextArea);
commentTextArea.setBounds(0, 0, 100, 100);
revalidate();
repaint();
}
}
【问题讨论】:
-
避免使用
null布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正。看看Why is it frowned upon to use a null layout in SWING? -
也可以查看Laying Out Components Within a Container 了解更多想法
-
JTextArea commentTextArea = new JTextArea(10, 10);..commentTextArea.setBounds(0, 0, 100, 100);要更改文本区域的大小,请更改行数或列数或字体大小。要更改位置,最简单的方法是添加EmptyBorder。另请参阅:Combinations of layout managers 和 white space 的布局填充和边框。
标签: java swing layout-manager null-layout-manager setbounds