javaGUI–监听器02

java
Author

dd21

Published

December 5, 2022

在这里插入图片描述 点击 在这里插入图片描述

package cn.usts.edu.lesson02;

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

public class TestActionEvent {

    public static void main(String[] args) {


        Frame frame = new Frame("action Event");
        Button button = new Button();
        frame.add(button,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        // 按钮监听
        MyActionListener myActionListener = new MyActionListener();
        // addActionListener需要一个ActionListener于是我们创建了一个myActionListener
        button.addActionListener(myActionListener);

        // 关闭
        myClose(frame);

    }


    // 监听关闭按钮
    private static void myClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}


class MyActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("监听到按钮动作");
    }
}