代码
import javax.swing.*;
import java.awt.*;
public class C5Ex1_2 {
final static int WIDTH = 400;
final static int HEIGHT = 400;
public C5Ex1_2() {
JFrame jf = new JFrame("program 1");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(WIDTH, HEIGHT);
JPanel panel = new JPanel();
jf.setContentPane(panel);
panel.setLayout(new BorderLayout());
Box vbox = Box.createVerticalBox();
// panel.setLayout(vbox);
panel.add(vbox, BorderLayout.CENTER);
Box hBox=Box.createHorizontalBox();
hBox.setSize(WIDTH, 20);
JTextField tf_out = new JTextField(15);
tf_out.setMaximumSize(tf_out.getPreferredSize());
hBox.add(tf_out);
vbox.add(hBox);
String[] names = {
"1", "2", "3", "%", "ON",
"4", "5", "6", "=", "AC",
"7", "8", "9", ".", "+/-",
"0", "+", "-", "*", "C"
};
hBox = null;
for(int i=0;i
if(i%5==0) {
// if(hBox != null) {
// hBox.setMaximumSize(hBox.getPreferredSize());
// System.out.println("size:" + hBox.getSize() + ":i=" + i);
// }
System.out.println("i="+i);
hBox = Box.createHorizontalBox();
Dimension size = new Dimension(400, 40);
hBox.setPreferredSize(size);
vbox.setBackground(Color.red);
vbox.add(hBox);
}
JButton btn = new JButton(names[i]);
Dimension preferSize = new Dimension(50, 40);
btn.setPreferredSize(preferSize);
// btn.setSize(50, 40);
hBox.add(btn);
System.out.println("hBox" + hBox);
}
jf.setVisible(true);
}
public static void main(String[] args) {
new C5Ex1_2();
}
}
显示结果
为什么感觉 Box 越来越小了?还是 btn 设置大小不起做用?