正如 Jim 所说,如果您需要线性对齐组件,BoxLayout 是正确的选择。
这是一个例子:
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author nicholasdunn
*/
public class BoxLayoutExample extends JPanel {
public BoxLayoutExample() {
JPanel topPanel = new JPanel();
JPanel middlePanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEtchedBorder());
middlePanel.setBorder(BorderFactory.createEtchedBorder());
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
topPanel.add(new JLabel("Top"));
middlePanel.add(new JLabel("Middle"));
bottomPanel.add(new JLabel("Bottom"));
BoxLayout boxLayout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
setLayout(boxLayout);
add(topPanel);
add(middlePanel);
add(bottomPanel);
}
public static void main(String[] args) {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new BoxLayoutExample();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
您最好仔细阅读布局管理器的介绍以了解 LayoutManagers 的基本集。当需要做复杂的布局时,请使用MigLayout而不是尝试学习 GridBagLayout - 你会感谢我的。