设置网格宽度时,在JDialog w / GridBagLayout中重叠

时间:2015-01-31 06:15:59

标签: java jtextfield gridbaglayout

我正在尝试创建一个如下所示的JDialog:

enter image description here

但是JTextField跨越两列,以便它几乎到达" Find Next"按钮。但是,当我尝试将JTextField的网格宽度设置为2时,我得到了这个:

enter image description here

这是我的代码:

JDialog dialog = new JDialog(frame, "Find");
dialog.setPreferredSize(new Dimension(370, 129));
Point p = frame.getLocation();
dialog.setLocation(p.x + 53, p.y + 170);

Container c = dialog.getContentPane();
GridBagLayout gbl = new GridBagLayout();
c.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();

JLabel label = new JLabel("Find what:");
gbc.gridx = gbc.gridy = 0;
c.add(label, gbc);

JTextField field = new JTextField();
field.setMinimumSize(field.getPreferredSize());
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
c.add(field, gbc);

JButton findNext = new JButton("Find Next");
findNext.setPreferredSize(new Dimension(82, 23));
gbc.gridx = 3;
c.add(findNext, gbc);

JCheckBox check = new JCheckBox("Match case");
gbc.gridx = 0;
gbc.gridy = 1;
c.add(check, gbc);

JRadioButton up = new JRadioButton("Up"), down = new JRadioButton("Down");
ButtonGroup group = new ButtonGroup();
group.add(up);
group.add(down);
gbc.gridx = 1;
c.add(up, gbc);
gbc.gridx = 2;
c.add(down, gbc);

JButton cancel = new JButton("Cancel");
cancel.setPreferredSize(new Dimension(82, 23));
cancel.addActionListener(e2 -> dialog.dispose());
gbc.gridx = 3;
c.add(cancel, gbc);

Font f = new Font("Segoe UI", Font.PLAIN, 12);
c.setFont(f);
for (Component child : c.getComponents())
    child.setFont(f);

dialog.pack();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setResizable(false);
dialog.setVisible(true);

提前致谢!

1 个答案:

答案 0 :(得分:2)

所以有两个问题......

  1. 您将gridwidth设置为2,但从未重置gbc.gridwidth = 2;,这意味着GridBagConstraints的所有后续使用都有gridwidth 2
  2. 过度使用setPreferredSize,事实上,任何用途都是过度使用......
  3. ...解

    在重新使用gridwidth ...

    之前休息GridBagConstraints
    gbc.gridwidth = 2;
    c.add(field, gbc);
    
    gbc.gridwidth = 1;
    //...
    

    不要使用setPreferredSize,您不能控制可以在多个平台上更改组件所需大小的属性。

    有关更多讨论,请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

    使用setPreferredSize

    enter image description here

    没有setPrefferedSize

    enter image description here

    你能看到按钮之间的区别吗?

    如果您想在组件中添加填充,请使用EmptyBorder和/或GridBagConstraints#insets作为初学者