【发布时间】:2018-07-30 03:26:46
【问题描述】:
我正在尝试使用 GridBagLayout 在 JPanel 上定位组件,但我得到的输出与我的预期完全不同。希望在stackoverflow中与聪明的人一起弄清楚:)。
下面我提供了一段代码和程序的屏幕截图。我的问题是:
为什么 JLabel
Choose measure system to convert不在Y-axis = 1上?据我所知,c.gridy=1向下一个像素,但标签卡在顶部,框架标题中没有空间。而且,为什么它的位置如此奇怪,即不是真的在中心,也不是在开始?-
为什么
李>ComboBoxesFrom...和To...之间有这么大的空格,而ComboBoxTo...和TextFieldEnter value here...之间却没有空格?
代码如下:
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
getContentPane().add(container, BorderLayout.NORTH);
TitledBorder outputCenter;
GridBagConstraints c = new GridBagConstraints();
label = new JLabel("Choose measure system to convert");
label.setFont(new Font("Times New Roman", Font.PLAIN, 20));
c.gridx = 0;
c.gridy = 1;
container.add(label, c);
fromList = new JComboBox<String>(convertFrom);
c.gridx = 0;
c.gridy = 2;
container.add(fromList, c);
toList = new JComboBox<String>(convertTo);
c.gridx = 1;
c.gridy = 2;
container.add(toList, c);
//Field where user enters the value to be converted
input = new JTextField("Enter value here...");
input.setPreferredSize(new Dimension(150,30));;
input.setEditable(true);
input.setBackground(Color.WHITE);
input.setBorder(BorderFactory.createLineBorder(Color.BLACK));
input.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
input.setText("");}});
c.gridx = 2;
c.gridy = 2;
container.add(input, c);
这是截图:
编辑:如果我将代码更改为:
label = new JLabel("Choose measure system to convert");
label.setFont(new Font("Times New Roman", Font.PLAIN, 20));
c.gridx = 0;
c.gridy = 1;
container.add(label, c);
label = new JLabel("Choose measure system to convert");
label.setFont(new Font("Times New Roman", Font.PLAIN, 20));
c.gridx = 1; // changed this line
c.gridy = 1;
container.add(label, c);
这让我很困惑,为什么改变一个组件的位置会影响一切?
【问题讨论】:
-
This is very confusing me as why changing the position of one component effects everything?- 您将标签从第一列移到了第二列。每列的宽度由添加到该列的最大组件的宽度决定。因此,当您将标签从第一列移动到第二列时,列的宽度会随着添加到每列的每个组件而变化。 -
在第一个示例中,标签是最大的组件,位于第一列,“from”组合框位于该列的中心。在第二个示例中,标签在第二列中也是最大的,并且“to”组合框在该列中居中。阅读 Swing 教程中有关 [如何使用 GridBagLayout]() 的部分,以获取更多信息和所有约束的解释以及工作示例。
-
@camickr,谢谢!!!
标签: java swing layout-manager gridbaglayout