GridBagLayout中组件的大小不正确
问题描述:
我在Java中做了一个简单的接口。我想在上面有一个设置为200 * 20的JButton,并且在它的正下方有一个封装了JTextArea的JScrollPane。此字段的大小应该是放置它的JPanel的剩余宽度和高度(但最小为640 * 480),并且必须在使窗口变大/变小(直到其最小大小)时调整其大小。GridBagLayout中组件的大小不正确
我试着用GridBagLayout做这个,但是这似乎没有工作。有人知道我能如何解决这个问题吗?
//Initialize components
Dimension minSize = new Dimension(640, 480);
info = new JTextArea("hello");
info.setEditable(false);
JScrollPane scrollPane = new JScrollPane(info);
scrollPane.setMinimumSize(minSize);
JButton update = new JButton("update");
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints grid = new GridBagConstraints();
//add components
grid.fill = GridBagConstraints.NONE;
grid.anchor = GridBagConstraints.NORTHWEST;
grid.gridheight = 1;
grid.gridwidth = 1;
grid.weighty = 1.0;
grid.weightx = 1.0;
grid.gridx = 0;
grid.gridy = 0;
jp.add(update, grid);
grid.fill = GridBagConstraints.BOTH;
grid.gridx = 0;
grid.gridy = 1;
grid.weighty = 15;
grid.gridheight = 15;
grid.gridwidth = 15;
jp.add(scrollPane, grid);
this.add(jp,BorderLayout.NORTH);
这是现在的样子:如我之前描述这是不是我想要的; TextArea需要填满整个屏幕(所以它需要更高)。
我该怎么做?
答
this.add(jp, BorderLayout.CENTER);
作为指定in the documentation:
的组分根据它们的优选的尺寸和容器的大小的 约束布局。 NORTH和SOUTH组件 可能会水平拉伸;东部和西部组件可能是 垂直拉伸; CENTER组件可以水平和垂直拉伸 以填充上剩余的任何空间。
谢谢!这就是诀窍:)为什么它的工作? – 2013-04-07 21:17:02
粘贴文档以解释其工作原理。 – Aubin 2013-04-08 17:09:03