Java GradBagLayout不基于权重分布列
这就是我的GUI现在的样子: 我想让这三列平均分布。为此,我将每个权重设置为1/3。显然,它不起作用 以下是我创建框架的代码:Java GradBagLayout不基于权重分布列,java,swing,user-interface,Java,Swing,User Interface,这就是我的GUI现在的样子: 我想让这三列平均分布。为此,我将每个权重设置为1/3。显然,它不起作用 以下是我创建框架的代码: public static JPanel createLayout(int rows) { JPanel product = new JPanel(new GridBagLayout()); String[] lables = {"School ", "Advanced #", "Novice # "}; double weight
public static JPanel createLayout(int rows) {
JPanel product = new JPanel(new GridBagLayout());
String[] lables = {"School ", "Advanced #", "Novice # "};
double weight = .3333333333333;
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3, 3, 3, 3);
c.weightx = weight;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.gridy = 1;
for (int j = 0; j < lables.length; j++) {
c.gridx = j;
JLabel l = new JLabel(lables[j]);
product.add(l, c);
}
for (int i = 0; i < rows; i++) {
c.gridy++;
for (int j = 0; j < lables.length; j++) {
c.gridx = j;
JTextField f = new JTextField();
product.add(f, c);
}
}
c.gridy++;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.NONE;
JPanel b = new JPanel();
JButton add = new JButton("+");
b.add(add);
JButton delete = new JButton("-");
b.add(delete);
product.add(b, c);
return product;
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Debate Calculator");
JPanel debates = new JPanel();
frame.add(createLayout(5), BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
publicstaticjpanelcreatelayout(int行){
JPanel产品=新的JPanel(新的GridBagLayout());
String[]标签={“学校”、“高级”、“新手”};
双倍重量=.3333;
GridBagConstraints c=新的GridBagConstraints();
c、 插图=新插图(3,3,3,3);
c、 重量x=重量;
c、 填充=GridBagConstraints.HORIZONTAL;
c、 锚点=GridBagConstraints.CENTER;
c、 gridy=1;
对于(int j=0;j
问题在于底部的按钮栏。将该元素上的gridwidth设置为余数。问题在于,您的组件一开始的大小并不相同。我无法确切解释为什么它会这样做,但标签的大小各不相同,因为它们的字符数不同。我知道你试着把它做成同样的尺寸,但是a和W不一样
我将您的代码更改为使用以下代码,它似乎可以工作:
JTextField f = new JTextField(10);
现在,每个文本字段的宽度都大于标签的宽度,因此这是用于为每个列指定比例大小的宽度
您可以考虑使用网格布局。默认行为是使每个单元格大小相同