使用GridBagLayout放置组件(按钮和复选框)的位置不一致

时间:2014-01-08 01:04:47

标签: java swing layout gridbaglayout jcheckbox

以下代码是从Oracle tutorials复制并修改为放置除按钮以外的组件 - 标签和两个文本字段以及一个附加按钮。它产生它应该的形式(如下所示),所以你不必仔细检查前30行左右的代码:

enter image description here

如果我 UN 注释掉引用“框”的两行并注释掉引用button的相邻行,请查看复选框的放置位置。

enter image description here

我无法弄清楚是怎么回事。我想要最后一行的复选框,因为代码SEEMS要​​说它必须定位,但它不是。

我正在做的就是更改引用按钮的两个LINES而不是复选框。 GridBagLayout的规则是否依赖于组件? 我应该怎么做(为什么代码不能正常工作)才能获得最后一行的复选框?

public class Testy {   
  public static void addComponentsToPane(Container pane) {
      pane.setLayout(new GridBagLayout());
      GridBagConstraints c = new GridBagConstraints();
      c.fill = GridBagConstraints.HORIZONTAL; 
      c.weightx = 0.5;
      c.gridx = 0;      c.gridy = 0;
      JLabel label = new JLabel("Button 1 ");
      pane.add(label, c);
      JTextField text = new JTextField("Button 2 ");
      c.gridx = 1;      c.gridy = 0;
      pane.add(text, c);
      JButton button = new JButton("Button 3 ");
      c.gridx = 2;      c.gridy = 0;
      pane.add(button, c);
      text = new JTextField("LONG Text 4 ");
      c.ipady = 40;      
      c.weightx = 0.0;
      c.gridwidth = 3;
      c.gridx = 0;      c.gridy = 1;
      pane.add(text, c);
      button = new JButton("5 ");
      c.ipady = 0;       
      c.weighty = 1.0;   
      c.gridx = 1;      c.gridy = 2;    
      c.gridwidth = 2;   
      pane.add(button, c);
// Here's the part of the code in question
      button = new JButton("666");  // This placement is FINE, at bottom of form.
  //  JCheckBox box = new JCheckBox("Me?");   // "box" does NOT get placed on last line.
      c.weighty = 0;     
      c.gridx = 0;     c.gridy = 3;    
      c.gridwidth = 1;   
  //  pane.add(box);
      pane.add(button, c);
    }

以下是我删除的必需导入和两个方法,因此可以在不滚动的情况下看到上面的问题代码区域:

import java.awt.*;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

  private static void createAndShowGUI() /* calls addComponentsToPane() */{
        JFrame frame = new JFrame("GridBagLayoutDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) /* calls createAndShowGUI() */ {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }        });    }
}

1 个答案:

答案 0 :(得分:3)

//  pane.add(box);
    pane.add(button, c);

您只需使用正确的方法:

pane.add(box, c);

请参阅Container#add(Component comp)Container#add(Component comp, Object constraints)