GUI之事件监听

package day15;

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 EventListen {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Button button = new Button();
        //因为addActionListener()需要一个ActionListener,所以需要构造一个ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);

        frame.add(button, BorderLayout.CENTER);
        frame.pack();
        windowClose(frame);//关闭窗口
        frame.setVisible(true);

    }

    //关闭窗体的事件
    private static void windowClose(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("lalala");
    }
}
执行结果:

posted @ 2021-08-07 22:38  Eleanor123  阅读(29)  评论(0编辑  收藏  举报