窗体组件类结构
JPanel面板
- JPanel是一种中间层容器,它能容纳组件并将组件组合在一起,但它本身必须添加到其它容器中使用
JPanel构造方法
- JPanel() : 创建具有双缓冲和流布局的新 JPanel。
- JPanel(boolean isDoubleBuffered) :创建具有 FlowLayout 和指定缓冲策略的新 JPanel。
- JPanel(LayoutManager layout) :创建具有指定布局管理器的新缓冲 JPanel。
- JPanel(LayoutManager layout, boolean isDoubleBuffered) :创建具有指定布局管理器和缓冲策略的新 JPanel。
JPanel方法
- Component add(Component comp):将指定的组件追加到此容器的尾部
- void remove(Component comp):从容器中移除指定的组件
- void setFont(Font f):设置容器的字体
- void setLayout(LayoutManager mgr):设置容器的布局管理器
- void setBackground(Color c):设置组件的背景色
Demo
import javax.swing.*;
import java.awt.*;
public class Demo08 {
public static void main(String[] args) {
JFrame jFrame = new JFrame("父窗体");
Container container = jFrame.getContentPane();
//设置一个JPanel对象
JPanel jPanel = new JPanel();
//设置标签
JLabel jLabel = new JLabel("这是放在JPanel容器中的标签");
//将标签放进JPanel容器中
jPanel.add(jLabel);
//把JPanel组件放进container组件
container.add(jPanel);
//设置窗体大小
jFrame.setSize(400,200);
jFrame.setBackground(Color.white);
//设置窗体可见
jFrame.setVisible(true);
//设置窗体默认关闭方式
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Demo运行效果如下
JPanel默认流式布局管理器