zl程序教程

您现在的位置是:首页 >  Java

当前栏目

[javaSE] GUI(事件监听机制)

2023-02-18 15:47:15 时间

外部动作——>事件源(组件)——>事件对象——>监听器

 

获取Frame对象,与上节一样

调用Frame对象的addWindowListener()方法,参数:WindowListener对象,WindowListener是个接口,里面有七个方法要实现,找实现子类WindowAdapter,匿名内部类重写windowClosing()方法,传递进来参数:WindowEvent对象

方法中,调用System.exit(0)

 

 

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class GuiDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Frame frame=new Frame("我是窗体");
        frame.setSize(400,300);
        frame.setLocation(500,200);
        frame.setLayout(new FlowLayout());
        
        Button button=new Button("按钮");
        frame.add(button);
        //关闭按钮
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        frame.setVisible(true);
    }

}