您的位置:首页 > 编程语言 > Java开发

java-事件驱动设计-窗口事件的处理

2016-05-28 13:57 453 查看
1.所有的方法全部实现,对于不关心的方法,也必须用空语句实现。testwindowevent 类继承了JFrame并实现接口windowListener,本例中的框架既是事件监听器也是事件源。

windowListener接口定义了几个抽象方法。在窗口不同时机处理窗口事件。

package first;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class TestWindowEvent extends JFrame implements WindowListener{

    public static void main(String[] args) {

        TestWindowEvent frame=new TestWindowEvent();

        frame.setLocationRelativeTo(null);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setTitle("window event");

        frame.setSize(200,180);

        frame.setVisible(true);//the set_up of jframe

    }

    public TestWindowEvent()

    {

        addWindowListener(this);//register window monitor        

    }

    //under achieve the way of implement

    

    @Override

    public void windowActivated(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window activated");

    }

    @Override

    public void windowClosed(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window closed");

    }

    @Override

    public void windowClosing(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window closing");

    }

    @Override

    public void windowDeactivated(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window deactivated");

    }

    @Override

    public void windowDeiconified(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window deiconified");

    }

    @Override

    public void windowIconified(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window iconified");

    }

    @Override

    public void windowOpened(WindowEvent arg0) {

        // TODO Auto-generated method stub

        System.out.println("window opened");

    }

}

2.通过java提供的适配器类简化程序

package first;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class TestAdapter extends JFrame{

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        TestAdapter frame=new TestAdapter();

        frame.setLocationRelativeTo(null);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setTitle("window event");

        frame.setSize(200,180);

        frame.setVisible(true);

    }

    public TestAdapter(){

        addWindowListener(new WindowAdapter() {

            public void windowActivated(WindowEvent event){

                System.out.println("window activated");

            }

            

        });

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: