setLayout(new GridLayout(3, 2));
add(new JButton("Button 1"));
add(new JButton("Button 2"));
add(new JButton("Button 3"));
add(new JButton("Button 4"));
add(new JButton("Button 5"));
add(new JButton("Button 6"));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GridLayoutExample example = new GridLayoutExample();
example.setVisible(true);
});
}
}
```
5. BoxLayout:箱式布局,按照指定的方向(水平或垂直)排列组件。
```java
import javax.swing.*;
import java.awt.*;
public class BoxLayoutExample extends JFrame {
public BoxLayoutExample() {
setTitle("BoxLayout Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(new JButton("Button 1"));
add(new JButton("Button 2"));
add(new JButton("Button 3"));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
BoxLayoutExample example = new BoxLayoutExample();
example.setVisible(true);
});
}
}
```