一、简介
JPanel为轻量级组件提供了通用容器,其自身是可以嵌套的。可以存放其他组件,比如JButton、JTextArea、JTextField,也可以将JPanel放入到JFrame窗体以及其他容器中。JPanel的默认布局是FlowLayout,也使用布局管理器(Layout Manager)对添加到JPanel中的组件(compnent)进行定位和大小设置。JPanel边界以及背景是可以设置。
二、构造函数
//创建JPanel,默认是布局是FlowLayout
JPanel()
//以指定的布局layout创建JPanel
JPanel(LayoutManager layout)
三、常用操作
//设置JPanel的布局方式
setLayout(LayoutManager mgr)
//设置JPanel的背景颜色
setBackground(Color bg)
//为JPanel添加组件
add(Component comp)
//向JPanel指定的索引处添加组件
add(Component comp, int index)
//以指定的约束向JPanel添加组件
add(Component comp, Object constraints)
//获取指定索引处的组件
Component getComponent(int n)
//获取指定坐标处的组件
Component getComponentAt(int x, int y)
//获取此Panel所包含的所有组件
Component[] getComponents()
四、常用事件
- 键盘事件
panel.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});
- 鼠标事件
panel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
- 鼠标移动事件
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
});
五、示例
示例中的窗体展示了两个JPanel,一个采用默认布局,一个采用绝对布局。
public class TestJPane extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new TestJPane();
}
public TestJPane() {
initFrame();
}
private void initFrame() {
this.setTitle("JPanel测试");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponents();
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void addComponents() {
//设置窗体容器的布局为2*1的网格布局
this.setLayout(new GridLayout(2, 1));
//panel1默认布局FlowLayout
JPanel panel1 = new JPanel();
panel1.setBackground(new Color(255, 182, 193));
panel1.add(new JLabel("测试标签11"));
panel1.add(new JLabel("测试标签12"));
this.add(panel1);
//panel2绝对布局
JPanel panel2 = new JPanel(null);
panel2.setBackground(new Color(200, 182, 193));
JLabel lb21 = new JLabel("测试标签21");
lb21.setBounds(20, 20, 100, 25);
panel2.add(lb21);
JLabel lb22 = new JLabel("测试标签22");
lb22.setBounds(20, 60, 100, 25);
panel2.add(lb22);
this.add(panel2);
}
}