GUI 监听事件 (两个按钮,实现同一个监听)

编写代码 TestActionTwo测试类

package com.xiang.lesson02;

import org.w3c.dom.Node;

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 TestActionTwo {
    //两个按钮,实现同一个监听
//    开始----------结束
    public static void main(String[] args) {
        Frame frame = new Frame();

        Button btn1 = new Button("start");
        Button btn2 = new Button("stop");
        btn1.setActionCommand("btn1-start");
        btn2.setActionCommand("btn1-stop");
        MyMonitor monitor = new MyMonitor();
        btn1.addActionListener(monitor);
        btn2.addActionListener(monitor);

        frame.add(btn1, BorderLayout.SOUTH);
        frame.add(btn2, BorderLayout.NORTH);



        test(frame);
    }

    public static void test(Frame frame) {
        frame.setVisible(true);
        frame.setBackground(Color.green);
        frame.setBounds(400, 400, 400, 400);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }

        });
    }
}



class MyMonitor implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了:mag" + e.getActionCommand());
    }
}

运行结果

posted @ 2021-08-05 18:30  阿向向  阅读(146)  评论(0编辑  收藏  举报