理论上bt1和bt2应该是左对齐的呀,为什么会出现这样的情况?
请看代码:
package testgui;
import javax.swing.*;
public class TestGUI {
JFrame jf = new JFrame();
JButton bt1 = new JButton("bt1");
JButton bt2 = new JButton("bt2");
Box box1 = Box.createHorizontalBox();
Box box2 = Box.createVerticalBox();
public void init(){
box1.add(bt1);
box2.add(box1);
box2.add(bt2);
jf.add(box2);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
public static void main(String[] args) {
new TestGUI().init();
}
}
首先你要搞清楚你现在的层次关系
jf中嵌套了box2,box2是居中的。
box2嵌套了box1和bt2,它们是上下并列的。
box1是水平扩展的并且它又嵌套了bt1,注意box1的宽度比bt2大。
因为刚才说了,box2是居中对齐的(而不是左对齐),所以box1宽度大,它就往左偏,而bt2窄,就往右偏。