繁体   English   中英

GridBagLayout对齐标签

[英]GridBagLayout aligning labels

我一直在弄乱GridBagLayout,并且遇到了一些麻烦。 首先,我试图使标签从左上角开始,这是我完成的:

    JPanel right = new JPanel(new GridBagLayout());
    right.setPreferredSize(new Dimension(333,600));

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;

    JLabel testLabel = new JLabel();
    testLabel.setText("Test");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.weightx = 1;
    right.add(testLabel, gbc);

现在,我想在此标签下直接添加另一个标签:

    JLabel test2Label = new JLabel();
    test2Label.setText("test2");
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.weighty = 1;
    gbc.weightx = 1;
    right.add(test2Label, gbc);

而不是将其直接放在第一个面板的下面,而是将其放置在面板的中间。 这是因为我认为是weighty和weightx,但是如果我更改它们,则不会将标签放在左上方。 我该如何运作? 抱歉,如果不清楚,英语不是我的最佳语言,所以请告诉我您是否需要澄清。 -谢谢

如果我对您的理解正确,那么以下代码应为答案。 weightx和weighty决定如何将组件中的可用空间分配给其子组件-值越大,空间越多(此处更多信息: Java GridBagLayout中的Weightx和Weighty ),但是如果您将所有组件的值都保留为零,则它们全部将居中。

因此,在您的情况下,最好的解决方案是将整个剩余空间留给第二个组件。

GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;

JLabel testLabel = new JLabel();
testLabel.setText("Test");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
right.add(testLabel, gbc);

JLabel test2Label = new JLabel();
test2Label.setText("test2");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weighty = 1;
gbc.weightx = 1;
right.add(test2Label, gbc);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM