【问题标题】:GridBagLayout aligning labelsGridBagLayout 对齐标签
【发布时间】:2015-06-20 01:51:04
【问题描述】:

我一直在搞乱 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);

而不是将它直接放在第一个下面,而是将它放在面板的中间。这是因为我认为的重量和重量x,但如果我改变这些,那么它不会将标签放在左上角。我怎样才能让它工作?抱歉,如果不清楚,英语不是我最好的语言,所以如果您需要我澄清,请告诉我。 -谢谢

【问题讨论】:

    标签: java


    【解决方案1】:

    如果我理解正确,下面的代码应该是答案。 weightx 和 weighty 决定如何将组件中的可用空间分配给其子组件 - 值越大,空间越多(在此处阅读更多内容:Weightx and Weighty in Java GridBagLayout)但如果您将所有组件的值设为零,它们都将居中.

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-05
      • 2014-06-04
      • 2013-01-23
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多