事件监听

事件监听

本文介绍java中gui的事件监听功能。

给按钮添加功能

以下代码使按钮每次被点击就打印信息:

package com.cxf.gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonAction {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setSize(400,300);
        frame.setVisible(true);

        Button button = new Button("button");
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);

        frame.add(button);
    }

}
class MyActionListener implements ActionListener{

    public void actionPerformed(ActionEvent e){
        System.out.println("button clicked");
    }
}

上面的代码中对button增加了监听事件myActionListener,而监听事件由java自带接口ActionListener继承而来。接口可以理解为类的抽象,如果类是对象的上一级,那么接口就是类的上一级。点击button希望实现的功能就写在监听事件中,此处是打印‘button clicked’。

输出结果:

button clicked
button clicked

每单击一次button,就会输出一次button clicked。

使窗口得以关闭

以下代码对Frame增加点击叉号关闭窗口的功能:

package com.cxf.gui;

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

public class FrameAction {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setSize(400,300);
        frame.setVisible(true);
        windowClose(frame);
    }
    
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });

    }

}

上面的代码给frame增加监听事件WindowAdapter,当点击叉号时,调用WindowAdapter中的方法windowClosing,退出系统。

输出结果:

点击右上角叉号则窗口关闭。

两个按钮,同一个事件

事件监听让组件在发生特定操作时,进行预设的事件。比如按钮被点击时,进行文字输出。

预设的事件可以被共用,以下代码做出展示:

package com.cxf.gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SameEvent {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        MyMonitor myMonitor = new MyMonitor();

        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);

        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.setVisible(true);
        frame.setSize(400,300);
    }
}

class MyMonitor implements ActionListener{
    public void actionPerformed(ActionEvent e){
        System.out.println("clicked");
    }
}

输出结果:

clicked
clicked
clicked
clicked

两个按钮点击都会产生文字输出。而代码中只设置了一个监听事件,两个代码共用了这个监听事件。

posted on 2021-09-13 10:23  菜小疯  阅读(55)  评论(0)    收藏  举报