如何以格式向JFrame添加许多组件

时间:2023-01-29 09:20:14

I have a JPanel, 4 ComboBoxes, and a button. I want to have a 700 x 500 JFrame, with the panel taking up the left 500 x 500. The right side I want, vertically, 2 combo boxes, another 2 combo boxes, and then the button. Hopefully this makes sense: I just want to have them all visible and I want the boxes paired in groups of 2. Example code of what I've tried is here:

我有一个JPanel,4个ComboBoxes和一个按钮。我希望有一个700 x 500 JFrame,面板占据左侧500 x 500.我想要的右侧,垂直,2个组合框,另外2个组合框,然后是按钮。希望这是有道理的:我只想让它们全部可见,我希望盒子组成2组。我尝试过的示例代码在这里:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JButton;

public class Test extends JFrame{

public Test () {
    super();
    //setLayout(new FlowLayout());
    JPanel canvas = new JPanel();
    canvas.setBackground(Color.red);
    canvas.setSize(500, 500);
    JComboBox field1 = new JComboBox();
    JComboBox field2 = new JComboBox();
    JComboBox field3 = new JComboBox();
    JComboBox field4 = new JComboBox();      
    JButton button = new JButton();
    JPanel info = new JPanel();
    info.setBackground(Color.blue);
    info.add(field1, BorderLayout.NORTH);
    info.add(field2, BorderLayout.EAST);
    info.add(field3, BorderLayout.CENTER);
    info.add(field4, BorderLayout.WEST);
    info.add(button, BorderLayout.SOUTH);
    add(info, BorderLayout.EAST);
    add(canvas, BorderLayout.WEST);
    setTitle("TEST");
setSize(700, 500);
}

public static void main (String[] args) {
    JFrame testFrame = new Test();
    testFrame.setVisible(true);
}

}

Any help or suggestions about how to go about laying this out would be great.

任何关于如何解决这个问题的帮助或建议都会很棒。

1 个解决方案

#1


1  

If you want your combo buttons and the button vertically stacked on top of each other, I would use a grid layout instead of a border layout. Just make the border layout have 1 column and 5 rows.

如果您希望组合按钮和按钮垂直堆叠在一起,我会使用网格布局而不是边框​​布局。只需使边框布局有1列5行。

#1


1  

If you want your combo buttons and the button vertically stacked on top of each other, I would use a grid layout instead of a border layout. Just make the border layout have 1 column and 5 rows.

如果您希望组合按钮和按钮垂直堆叠在一起,我会使用网格布局而不是边框​​布局。只需使边框布局有1列5行。