BoxLayout
类以堆叠方式排列组件,使它们彼此叠加或排成行。它提供了FlowLayout
的灵活性。下面的例子展示了BoxLayout
的用法。
示例
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing BoxLayout布局(示例)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.add(new JButton("Java"));
panel.add(new JButton("Python"));
panel.add(new JButton("MySQL"));
panel.add(new JButton("Oracle"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
执行上面示例代码,得到以下结果: