代码
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<names.length;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 设置大小不起做用?
1
nekolr 2019-01-08 08:24:03 +08:00 via Android
别 swing 了,上 java fx 吧
|
2
jcsmallming 2019-01-08 14:09:52 +08:00 1
事实上你并没有设置按钮的大小,这里按钮的大小是根据按钮上的数字自动调整的,你可以试试把按钮的文字全部换成同一个数字验证下,就能完全对齐了
|
3
chenqh OP @jcsmallming btn.setPreferredSize(preferSize);这个不能设置按钮大小吗?
|
5
jcsmallming 2019-01-08 16:51:08 +08:00 1
@chenqh
把 JButton btn = new JButton(names[i]); Dimension preferSize = new Dimension(50, 40); btn.setPreferredSize(preferSize); 改成 JButton btn = new JButton(names[i]); Dimension preferSize = new Dimension(50, 40); btn.setBorder(BorderFactory.createRaisedBevelBorder()); btn.setMaximumSize(preferSize); btn.setPreferredSize(preferSize); 这样子就可以了 |
6
chenqh OP @jcsmallming 谢谢
|
7
jcsmallming 2019-01-08 16:53:26 +08:00
|
8
jcsmallming 2019-01-08 16:55:22 +08:00
@chenqh 不用客气,能帮上忙就好
|
9
chenqh OP @jcsmallming 我就需要这样的效果,大佬 NB
|