gpt4 book ai didi

java - 调整Gridbag布局

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:24 24 4
gpt4 key购买 nike

我正在尝试在 java 中使用 GRIDBAG 布局来实现此布局

public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

JLabel label1,label2,label3,result,title;
JButton calculate_btn;
JTextField side1,side2,side3;

pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}


title = new JLabel("Area of Triangle");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = -1;
pane.add(title, c);



label1 = new JLabel("Side 1: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 1;
pane.add(label1, c);

label2 = new JLabel("Side 2: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 2;
pane.add(label2, c);


label3 = new JLabel("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 3;
pane.add(label3, c);

side1 = new JTextField(" ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 1;
pane.add(side1, c);

side2 = new JTextField("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 2;
pane.add(side2, c);

side3 = new JTextField("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 3;
pane.add(side3, c);

calculate_btn = new JButton("Calculate");
//c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 30; //make this component tall
c.weightx = 0.5;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 5;
pane.add(calculate_btn, c);

result = new JLabel("Result displayed here");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 7;
pane.add(result, c);


}

所以上面的代码基本上只是将添加到 GUI 的组件,但我并没有完全得到我想要的,这就是我想要实现的目标

enter image description here

但这就是我用上面的代码得到的结果

enter image description here

因此,当我编译上面的代码时,我最终得到的结果是,如果可能的话,我不希望用户调整窗口大小,我猜测一些具有窗口属性之一的 boolean 值..

最佳答案

问题是您设置的 ipady 会垂直“拉伸(stretch)”您的组件。您可能正在寻找 insets 属性:http://docs.oracle.com/javase/7/docs/api/java/awt/GridBagConstraints.html#insets

尝试使用这个:

c.insets = new Insets(10, 0, 10, 0);

关于java - 调整Gridbag布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12796417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com