Why does GridBagLayout center my components instead of putting it in the corner?

為{幸葍}努か 提交于 2019-12-04 22:56:45

Add constraints.weighty = 1; to the JLabel constraints and constraints.anchor = GridBagConstraints.NORTHWEST; to the TextField constraints.

EDIT:

From Oracle's GridBagLayout guide:

Larger numbers indicate that the component's row or column should get more space. For each column, the weight is related to the highest weightx specified for a component within that column, with each multicolumn component's weight being split somehow between the columns the component is in. Similarly, each row's weight is related to the highest weighty specified for a component within that row. Extra space tends to go toward the rightmost column and bottom row.

You need to read further down in the Swing tutorial for the section on weightX/weightY where it states:

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container.

You specified a weightX but not a weightY.

Edit, it's more complicated than I thought. It appears you also need to specify:

constraints.anchor = GridBagConstraints.FIRST_LINE_START;

for both components in addiation to the weighty.

You can achieve this by using a trick, add a dummy component after your row and expand it to fill the vertical space. Also you can re-use the constraints, no need to create a new object:

EDIT: ok forget the trick :( The right way is as Deon Botha and BenCole said, I've updated my code using the anchor

Please DON'T accept this answer, accept either Deon's or Ben's

public class MainFrame extends JFrame { 
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

public MainFrame() {
    super();
    setBounds(100, 100, 500, 375);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container mainContainer = getContentPane();
    mainContainer.setLayout(new GridBagLayout());       

    JLabel someLabel = new JLabel("Label 1:");
    JTextField someText = new JTextField(30);

    GridBagConstraints constraints = new GridBagConstraints();
    constraints.anchor = GridBagConstraints.FIRST_LINE_START;

    constraints.gridx = 0;
    constraints.gridy = 0;    
    constraints.weightx = 1.0;
    mainContainer.add(someLabel, constraints);      

    constraints.gridx = 1;                       
    constraints.weightx = 1.0;
    constraints.weighty = 1.0;        
    mainContainer.add(someText, constraints);                       
}
}

I may not be answering your question directly, but trust me you should do your trial and erros on the layouts with an IDE. I personally suggests Netbeans. There you can drag and drop and then take a look over the properties. At first you would have some default values given in the property inspector and hence less auto generated code for that. But then, once you start playing with the layouts, you can see the code and get a nice understanding of knowing what you do how you do.

This worked for me:

public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel2 = new javax.swing.JPanel();
        jComboBox3 = new javax.swing.JComboBox();
        jComboBox4 = new javax.swing.JComboBox();
        jComboBox5 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 204, 51));
        setMinimumSize(new java.awt.Dimension(800, 600));
        getContentPane().setLayout(null);

        jPanel2.setLayout(new java.awt.GridBagLayout());

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        jPanel2.add(jComboBox3, gridBagConstraints);

        jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        jPanel2.add(jComboBox4, gridBagConstraints);

        jComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel2.add(jComboBox5, gridBagConstraints);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(30, 40, 150, 260);

        pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JComboBox jComboBox5;
    private javax.swing.JPanel jPanel2;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!