组件:
所有组件都继承自javax.swing.JComponent。
任意组件上都可以放置组件,但大部分情况下,交互组件会放在框架、面板等背景组件上。
背景组件
比如,框架 JFrame、 面板JPanel
交互组件
比如,按钮JButton、复选框JCheckBox、文本输入框JTextField
布局管理器
框架有自己的布局管理器,面板有自己的布局管理器。
BorderLayout
BorderLayout是框架JFrame默认的布局管理器,该管理器会把背景组件分成5个区域:EAST|SOUTH|WEST|NORTH|CENTER,且每个区域只能放一个组件。
按钮放东南西北
import javax.swing.*;
import java.awt.*;
public class Test{
public static void main(String[] args){
Test test = new Test();
test.demo();
}
public void demo(){
JFrame frame = new JFrame();
JButton east = new JButton("east");
JButton west = new JButton("west");
JButton south = new JButton("south");
JButton north = new JButton("north");
frame.getContentPane().add(BorderLayout.EAST,east);
frame.getContentPane().add(BorderLayout.WEST,west);
frame.getContentPane().add(BorderLayout.SOUTH,south);
frame.getContentPane().add(BorderLayout.NORTH,north);
frame.setSize(300,300);
frame.setVisible(true);
}
}
FlowLayout
FlowLayout是面板JPanel
默认的布局管理器,该管理器会按照组件加入的顺序,将组件从左到右、从上到下(发生换行时) 排列。
import javax.swing.*;
import java.awt.*;
public class Test{
public static void main(String[] args){
Test test = new Test();
test.demo();
}
public void demo(){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton("click me");
panel.add(button);
JButton button2 = new JButton("click metoo");
panel.add(button2);
frame.getContentPane().add(BorderLayout.EAST,panel);
frame.setSize(300,300);
frame.setVisible(true);
}
}