Day46--frame.add()语法
基本语法形式
:
frame.add(component);
frame
:这是一个JFrame
对象(或者是实现了Container
接口的容器对象),代表图形用户界面中的窗口或者一个容器,用于容纳其他组件。component
:是要添加到frame
中的组件对象,比如JButton
(按钮)、JLabel
(标签)、JTextField
(文本框)等。例如:
import javax.swing.JButton;
import javax.swing.JFrame;
public class AddComponentSyntaxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Syntax Example");
JButton button = new JButton("A Button");
frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
BorderLayout 布局
:
frame.add(component, position);
- 除了组件对象,还需要指定位置参数
position
。position
可以是BorderLayout
类中定义的常量,如BorderLayout.NORTH
(北)、BorderLayout.SOUTH
(南)、BorderLayout.EAST
(东)、BorderLayout.WEST
(西)、BorderLayout.CENTER
(中)。例如:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
public class BorderLayoutSyntaxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Border Layout Syntax Example");
JPanel panel = new JPanel(new BorderLayout());
JButton northButton = new JButton("North");
JButton southButton = new JButton("South");
JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JButton centerButton = new JButton("Center");
panel.add(northButton, BorderLayout.NORTH);
panel.add(southButton, BorderLayout.SOUTH);
panel.add(eastButton, BorderLayout.EAST);
panel.add(westButton, BorderLayout.WEST);
panel.add(centerButton, BorderLayout.CENTER);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GridLayout 布局
:
frame.add(component);
(基本形式不变,但组件添加顺序按网格布局规则)
- 例如,在一个
2x2
的GridLayout
布局中添加组件:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class GridLayoutSyntaxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Grid Layout Syntax Example");
JPanel panel = new JPanel(new GridLayout(2, 2));
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
标签:BorderLayout,--,frame,add,new,Day46,JButton,panel
From: https://www.cnblogs.com/xiaokunzhong/p/18604509