将组件放在GridBagLayout中

时间:2012-09-14 07:33:58

标签: swing

我正试图像这样放置JLabel和JTextfield,

      First Name       Textbox        -> First Name is a label named as lblFirstname
      Last Name        Textbox        TextBox is JTextField

尝试使用GridBagLayout,

应用的约束是,

      lblFirstNameCons.gridx = 0;
      lblLastNameCons.gridy = 0;

      txtFirstName.gridx = 0;
      txtLastNameCons.gridy = 3;

我得到这样的输出,

      First NameTextbox  -> There is no space and also, the JTextField is almost invisible.  

2 个答案:

答案 0 :(得分:2)

布局应该是这样的。括号中的值是gridx和gridy(grix,gridy):

First Name (0, 0)       Textbox (1, 0)
Last Name  (0, 1)       Textbox (1, 1)

答案 1 :(得分:1)

  1. 您应确保将GridBagConstraint的fill属性设置为HORIZONTAL以用于文本字段,并确保weightx设置为大于0的内容
  2. 或者您可以在文本字段中指明要显示的所需列数(这最终会影响文本字段的首选大小)。
  3. 以下示例显示:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.net.MalformedURLException;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class TestGridBagLayout {
    
        protected void initUI() throws MalformedURLException {
            final JFrame frame = new JFrame();
            frame.setTitle(TestGridBagLayout.class.getSimpleName());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JPanel panel = new JPanel(new GridBagLayout());
            JLabel firstName = new JLabel("First name:");
            JLabel lastName = new JLabel("Last name:");
            JTextField firstNameTF = new JTextField();
            JTextField lastNameTF = new JTextField();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(3, 3, 3, 3);
            gbc.weightx = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.CENTER;
            panel.add(firstName, gbc);
            gbc.weightx = 1;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(firstNameTF, gbc);
            gbc.gridwidth = 1;
            gbc.weightx = 0;
            panel.add(lastName, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            panel.add(lastNameTF, gbc);
            frame.add(panel);
            frame.setSize(300, 200);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new TestGridBagLayout().initUI();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
    }