在Java中,布局(layout)用于控制和管理组件在容器中的位置和大小。Java提供了几种常用的布局管理器,例如:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));
frame.pack();
frame.setVisible(true);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2, 3));
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));
frame.add(new JButton("Button 5"));
frame.add(new JButton("Button 6"));
frame.pack();
frame.setVisible(true);
JFrame frame = new JFrame();
frame.setLayout(new CardLayout());
JPanel card1 = new JPanel();
card1.add(new JLabel("Card 1"));
frame.add(card1, "Card 1");
JPanel card2 = new JPanel();
card2.add(new JLabel("Card 2"));
frame.add(card2, "Card 2");
CardLayout layout = (CardLayout) frame.getContentPane().getLayout();
layout.show(frame.getContentPane(), "Card 2");
frame.pack();
frame.setVisible(true);
以上只是一些常见的布局管理器示例,Java还提供了其他布局管理器,如GridBagLayout(网格包布局)和BoxLayout(盒子布局)等。根据实际需求选择合适的布局管理器来实现界面布局。