在Java中,使用Swing庫中的JPanel來布局組件。以下是一些常用的布局管理器及其用法:
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Label 1"));
panel.add(new JButton("Button 1"));
panel.add(new JTextField(10));
frame.add(panel);
frame.setVisible(true);
}
}
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JLabel("Label 1"), BorderLayout.NORTH);
panel.add(new JButton("Button 1"), BorderLayout.CENTER);
panel.add(new JTextField(10), BorderLayout.SOUTH);
frame.add(panel);
frame.setVisible(true);
}
}
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
for (int i = 1; i <= 6; i++) {
panel.add(new JLabel("Label " + i));
panel.add(new JButton("Button " + i));
}
frame.add(panel);
frame.setVisible(true);
}
}
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (int i = 1; i <= 6; i++) {
panel.add(new JLabel("Label " + i));
panel.add(Box.createVerticalStrut(50));
panel.add(new JButton("Button " + i));
}
frame.add(panel);
frame.setVisible(true);
}
}
這些示例展示了如何使用不同的布局管理器在JPanel中添加組件。你可以根據需要選擇合適的布局管理器。