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

时间:2013-04-06 02:46:49

标签: java swing layout

我有一个JPanel,4个ComboBox和一个按钮。我希望有一个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);
}

}

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

1 个答案:

答案 0 :(得分:1)

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