我正在尝试使用 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 中的组件,但我并没有完全得到我想要的,这就是我想要实现的
但这就是我用上面的代码得到的
因此,当我编译上面的内容时,我最终得到的结果是,如果可能的话,我也不希望用户调整窗口大小,我猜想一些带有窗口属性之一的布尔值..