为什么 GridBagLayout 将我的组件居中而不是放在角落?

发布于 2024-12-02 13:16:19 字数 1905 浏览 0 评论 0原文

到目前为止,我设法尽可能避免使用 GridBagLayout (手动代码),但这次我无法避免它,我正在阅读 SUN 的教程 GridBagLayout 到目前为止进展并不顺利。我想我误解了一些东西。
例如,我尝试使用以下代码(类似于 SUN 帖子中的代码):

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();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container mainContainer = getContentPane();

        mainContainer.setLayout(new GridBagLayout());       

        //add label
        JLabel someLabel = new JLabel("Label 1:");
        GridBagConstraints constraints = new GridBagConstraints();

        constraints.gridx = 0;
        constraints.gridy = 0;
        //constraints.anchor = GridBagConstraints.FIRST_LINE_START;
        //constraints.weightx = 0.5;
        mainContainer.add(someLabel, constraints);      

        JTextField someText = new JTextField(30);

        constraints = new GridBagConstraints();

        constraints.gridx = 1;
        constraints.gridy = 0;
        constraints.weightx = 0.5;
        mainContainer.add(someText, constraints);

        //
    }

}

我在框架的中心中获得了一个相邻的标签和文本字段。
但我期望它们会出现在左上角,因为标签的 gridx 和 gridy 为 0。
即使我设置 constraints.anchor = GridBagConstraints.FIRST_LINE_START; 仍然是相同的结果。
我这里错了吗?
来自太阳报的帖子:

指定组件左上角的行和列。这 最左边的列有地址 gridx=0,顶行有地址 网格=0。

So far I managed to avoid using the GridBagLayout (by hand code) as much as possible, but I could not avoid it this time and I am reading the SUN's tutorial GridBagLayout
So far it is not going well. I think I am missunderstanding something.
For example I try the following code (similar to the one in SUN's post):

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();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container mainContainer = getContentPane();

        mainContainer.setLayout(new GridBagLayout());       

        //add label
        JLabel someLabel = new JLabel("Label 1:");
        GridBagConstraints constraints = new GridBagConstraints();

        constraints.gridx = 0;
        constraints.gridy = 0;
        //constraints.anchor = GridBagConstraints.FIRST_LINE_START;
        //constraints.weightx = 0.5;
        mainContainer.add(someLabel, constraints);      

        JTextField someText = new JTextField(30);

        constraints = new GridBagConstraints();

        constraints.gridx = 1;
        constraints.gridy = 0;
        constraints.weightx = 0.5;
        mainContainer.add(someText, constraints);

        //
    }

}

I get the label and the textfield one next to the other in the center of the frame.
But I was expecting that they would show up in the top left corner since the gridx and gridy is 0 for the label.
Even if I set constraints.anchor = GridBagConstraints.FIRST_LINE_START; still the same result.
Am I wrong here?
From the SUN's post:

Specify the row and column at the upper left of the component. The
leftmost column has address gridx=0 and the top row has address
gridy=0.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

遗失的美好 2024-12-09 13:16:19

constraints.weighty = 1; 添加到 JLabel 约束,并将 constraints.anchor = GridBagConstraints.NORTHWEST; 添加到 TextField 约束。

编辑:

来自 Oracle 的 GridBagLayout 指南

数字越大表示组件的行或列应该获得更多的空间。对于每一列,权重与为该列中的组件指定的最高权重相关,每个多列组件的权重以某种方式在该组件所在的列之间分割。类似地,每行的权重与为该组件指定的最高权重相关。该行中的组件。额外的空间往往会流向最右边的列和底部的行。

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.

趴在窗边数星星i 2024-12-09 13:16:19

您需要在 Swing 教程中进一步阅读有关 weightX/weightY 的部分,其中指出:

除非您为weightx或weighty指定至少一个非零值,否则所有组件都会聚集在一起一起放在容器的中心。

您指定了weightX,但没有指定weightY。

编辑一下,比我想象的要复杂。看来您还需要指定:

constraints.anchor = GridBagConstraints.FIRST_LINE_START;

除了权重之外,还需要为两个组件指定:

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.

若沐 2024-12-09 13:16:19

您可以通过使用一个技巧来实现这一点,在行后面添加一个虚拟组件并将其扩展以填充垂直空间。您也可以重复使用约束,无需创建新对象:

编辑:好吧,忘记技巧了:(正确的方法是 Deon Botha 和 BenCole 所说的,我已经使用锚点更新了我的代码,

DON 'T 接受这个答案,接受 Deon 或 Ben 的答案

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);                       
}
}

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);                       
}
}
旧人哭 2024-12-09 13:16:19

我可能不会直接回答你的问题,但相信我,你应该使用 IDE 在布局上进行尝试和错误。我个人建议 Netbeans。您可以在那里拖放,然后查看属性。首先,您会在属性检查器中给出一些默认值,因此自动生成的代码会较少。但是,一旦您开始使用布局,您就可以看到代码并很好地了解您要做什么。

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.

狠疯拽 2024-12-09 13:16:19

这对我有用:

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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文