GUI 面板实现 (解决了关闭事件)

编写代码 TestPanel测试类

package com.xiang.lesson01;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

//Panel 面板
public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        /*
        public Panel() {
        this(new FlowLayout());
    }
    FlowLayout---流布局
         */

//        设置布局
        frame.setLayout(null);
//        坐标
        frame.setBounds(300,300,600,600);
        frame.setBackground(Color.yellow);

//        设置panel
        panel.setBounds(100,100,400,400);
        panel.setBackground(Color.red);

//        frame.add(panel) frame 添加 面板
        frame.add(panel);

//        可见性
        frame.setVisible(true);

//        监听窗口,关闭事件
//        System.exit(0); 强制退出
//        适配器 模式;WindowAdapter()
        frame.addWindowListener(new WindowAdapter() {
            //窗口关闭要作的事情
            @Override
            public void windowClosing(WindowEvent e) {
//                结束程序
                System.exit(0);
            }
        });
    }
}

运行结果

原文地址:https://www.cnblogs.com/d534/p/15104072.html