GUI容器之Frame

Frame

public class MyFrame {
    public static void main(String[] args) {

        //创建一个Frame对象
        Frame frame = new Frame("我的第一个Frame窗口");

        //此时的Frame只是占用了空间,还看不见
        //所以需要定义一些属性
        //1.设置可见性
        frame.setVisible(true);

        //2.设置大小
        frame.setSize(200,200);

        //3.设置位置
        frame.setLocation(100,100);

        //4.设置颜色
        frame.setBackground(Color.yellow);

        //是否可以改变大小
        frame.setResizable(false);

    }
}

尝试将Frame进行封装,并创建多个窗口

public class Test01 {
    public static void main(String[] args) {
        new MyFrame01(100,100,200,200,Color.BLACK);
        new MyFrame01(100,300,200,200,Color.YELLOW);
        new MyFrame01(300,100,200,200,Color.BLUE);
        new MyFrame01(300,300,200,200,Color.WHITE);
    }

}

//对Frame类进行封装
class MyFrame01 extends Frame {
    int id = 0;//对窗口进行计数

    public MyFrame01(int x,int y,int l,int w,Color color){

        this.setTitle("MyFrame01"+id);
        //同时设置大小、位置
        this.setBounds(x,y,l,w);
        //颜色
        this.setBackground(color);
        //可见性
        this.setVisible(true);

        this.id++;
    }

}

发现问题:窗口不能关闭

监听事件,监听窗口关闭事件 System.exit(0);

        //添加监听事件
        //适配器模式
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }
        });
posted @ 2020-03-27 16:15  shimmernight  阅读(147)  评论(0编辑  收藏  举报