上面的窗口是用下面的代码生成的,它使用了 3 个外部类。
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GridBagLayout{
JFrame frame;
public GridBagLayout() {
initComponents();
}
private void initComponents(){
JTextField text = new JTextField("",10);
JButton but1 = new JButton("button 1");
JButton but2 = new JButton("button 2");
JButton but3 = new JButton("button 3");
JLabel lab0 = new JLabel("Enter a sentence");
JLabel lab1 = new JLabel("test 1");
JLabel lab2 = new JLabel("test 2");
JLabel lab3 = new JLabel("test 3");
frame = new JFrame("TestGridBagLayout");
frame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
frame.setLayout(new java.awt.GridBagLayout());
frame.add(lab0, new GBConstraints(0,0));
frame.add(text, new GBConstraints(1,0));
frame.add(but1, new GBConstraints(0,1));
frame.add(lab1, new GBConstraints(1,1));
frame.add(but2, new GBConstraints(0,2));
frame.add(lab2, new GBConstraints(1,2));
frame.add(but3, new GBConstraints(0,3));
frame.add(lab3, new GBConstraints(1,3));
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
new GridBagLayout();
}
}
下面的窗口是通过将上面的 new GBConstraints 行更改为图片下方显示的行来生成的,关键是有几种相当简单的方法可以调整布局以使其看起来像你想要的那样——如何靠在一起和垂直对齐的方式,有两个问题。
frame.add(lab0, new GBConstraints(0,0).anchor(EAST));
frame.add(text, new GBConstraints(1,0).ipad(100, 0).anchor(WEST));
frame.add(but1, new GBConstraints(0,1));
frame.add(lab1, new GBConstraints(1,1));
frame.add(but2, new GBConstraints(0,2));
frame.add(lab2, new GBConstraints(1,2).insets(15, -15, 5, 5));
frame.add(but3, new GBConstraints(0,3).anchor(EAST));
frame.add(lab3, new GBConstraints(1,3).anchor(WEST));
请注意,上面的第二行在 GBConstraint 上添加了两个约束; @SplungeBob 在this thread 中提供的Fill、Anchor 和GBConstraints 类提供了灵活性。