在网格样式布局中为JButton设置固定大小

时间:2012-05-29 20:55:39

标签: java user-interface jbutton layout-manager

我想将16个按钮显示为4x4网格。每个按钮的大小应相同,并且间隙相等。

我已经能够设置间隙大小,但我无法减小按钮的大小。我基本上只使用它来进行组布局......

layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button1)
                    .addComponent(button5)
                    .addComponent(button9)
                    .addComponent(button13))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button2)
                    .addComponent(button6)
                    .addComponent(button10)
                    .addComponent(button14))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button3)
                    .addComponent(button7)
                    .addComponent(button11)
                    .addComponent(button15))
               .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(button4)
                    .addComponent(button8)
                    .addComponent(button12)
                    .addComponent(button16))
            );

            layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button1)
                    .addComponent(button2)
                    .addComponent(button3)
                    .addComponent(button4))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button5)
                    .addComponent(button6)
                    .addComponent(button7)
                    .addComponent(button8))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button9)
                    .addComponent(button10)
                    .addComponent(button11)
                    .addComponent(button12))
               .addGroup(layout.createParallelGroup(BASELINE)
                    .addComponent(button13)
                    .addComponent(button14)
                    .addComponent(button15)
                    .addComponent(button16))

有人可以用更好的方法帮助我。

2 个答案:

答案 0 :(得分:0)

您也可以尝试使用GridLayout()。这会将所有组件排列在网格中,行和列由参数定义。您可以使用

行创建它
GridLayout g = new GridLayout(rows, columns)

您需要导入AWT 所以你的代码看起来像:

GridLayout g = new GridLayout(4,4);
//Add it to your JPanel
myJpanel.setLayout(g);
//then
myJpanel.add(button1);
//the rest of your code

答案 1 :(得分:-1)

GroupLayout中每个组件的大小受三个值约束;最小尺寸,首选尺寸和最大尺寸

尝试:

button.setPreferredSize(new Dimension(50, 10));
相关问题