繁体   English   中英

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

[英]Setting a fixed size for JButtons in a grid-style layout

我想让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))

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

您也可以尝试使用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

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

尝试:

button.setPreferredSize(new Dimension(50, 10));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM