[英]Setting a fixed size for JButtons in a grid-style layout
I want to make 16 buttons display as a 4x4 grid. 我想让16个按钮显示为4x4网格。 Each button should be the same size, and have an equal gap.
每个按钮应具有相同的大小,并具有相等的间隙。
I have been able to set the gap size, but I can't reduce the size of the button. 我已经能够设置间隙大小,但是我不能减小按钮的大小。 I've basically used just this for group layout...
我基本上只是将其用于组布局...
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))
Could someone please help me with a better approach. 有人可以帮我更好的方法。
You could also try using a GridLayout(). 您也可以尝试使用GridLayout()。 This arranges all your components in a grid, the rows and columns are defined by the parameters.
这将所有组件排列在一个网格中,行和列由参数定义。 You create it using the line
您使用以下行创建它
GridLayout g = new GridLayout(rows, columns)
You need to import the AWT so your code would look like: 您需要导入AWT,以便您的代码如下所示:
GridLayout g = new GridLayout(4,4);
//Add it to your JPanel
myJpanel.setLayout(g);
//then
myJpanel.add(button1);
//the rest of your code
The size of each component in a GroupLayout is constrained by three values; GroupLayout中每个组件的大小受三个值约束; minimum size, preferred size and maximum size
最小尺寸,首选尺寸和最大尺寸
Try: 尝试:
button.setPreferredSize(new Dimension(50, 10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.