其他分享
首页 > 其他分享> > 事件监听

事件监听

作者:互联网


import com.sun.jdi.PathSearchingVirtualMachine;

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

public class TestActionEvent02 {
    public static void main(String[] args) {
      //两个按钮,实现一个监听
        //开始 停止
        Frame frame = new Frame("开始-停止");
        Button button1 = new Button("start");
        Button button2 = new Button("stop");

        //可以显示的定义出发会返回的命令,如果不显示定义,则会走默认值
        //可以多个按钮只写一个监听类
        button2.setActionCommand("button2-stop");

        MyMonitor myMonitor = new MyMonitor();

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

        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);

        frame.setVisible(true);

    }
}

class MyMonitor implements ActionListener{

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

多个按钮,共享一个事件

标签:Button,按钮,监听,button2,事件,new,import,frame
来源: https://www.cnblogs.com/m1573/p/15023809.html