[英]Buttons doesn't fill all available space when I use GridBagLayout in Java
I want to create an application with buttons arrayed into invisible table. 我想创建一个应用程序,其中的按钮排列成不可见的表格。 The buttons should fill all the available space inside the imaginary cells even when I´ll resize the frame.
即使我要调整框架的大小,按钮也应填充假想单元内部的所有可用空间。 I´m using Swing,
GridBagLayout
. 我正在使用Swing,
GridBagLayout
。 I've read some articles and the solution was to add .weightx=1
and .weighty=1
. 我已经阅读了一些文章,解决方案是添加
.weightx=1
和.weighty=1
。 Weightx
works perfect and it fill the gaps but weighty doesn't. Weightx
工作完美,填补了空白,但Weightx
却没有。 Buttons don´t extend into height of cell. 按钮不会延伸到单元格的高度。 Is there a problem with my code or is there something to add that solve my problem?
我的代码是否有问题或有什么要解决的问题? Or should I use absolutely another layout?
还是我绝对应该使用其他布局?
public class NewClass {
public void NewClass(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JButton B11 = new JButton("11");
panel.add(B11,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
JButton B12 = new JButton("12");
panel.add(B12,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JButton B21 = new JButton("21");
panel.add(B21,gbc);
gbc.gridx = 1;
gbc.gridy = 1;
JButton B22 = new JButton("22");
panel.add(B22,gbc);
frame.pack();
frame.setSize(800,400);
frame.setVisible(true);
}}
You're using the wrong GridBagConstraints#fill
field value, since the value you're using is telling the layout manager to fill the buttons horizontally only. 您使用了错误的
GridBagConstraints#fill
字段值,因为您使用的值告诉布局管理器仅水平填充按钮。
You need to change 你需要改变
gbc.fill = GridBagConstraints.HORIZONTAL;
to 至
// gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.BOTH;
if you want the buttons to fill both directions, both horizontally and vertically. 如果您希望按钮同时填充水平和垂直两个方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.