package com.lr.guifirstdemo;
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 testDemo06 {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBounds(200,200,500,200);
Button button = new Button("button-1");
button.setBackground(Color.BLUE);
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("aaa");
}
}
------------------------------------------------------
------------------------------------------------------
package com.lr.guifirstdemo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class testDemo07 {
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.pack();
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//获得按钮的信息
System.out.println("按钮被点击了msg: "+e.getActionCommand());
if (e.getActionCommand().equals("start")){
System.out.println("I love you");
}
if (e.getActionCommand().equals("stop")){
System.out.println("I hate you");
}
}
}
// 两个按钮公用一个监听事件,不需要每个按钮都写一个事件,提高效率
标签:12,java,frame,awt,public,2022,new,import,监听 From: https://www.cnblogs.com/RUI2022/p/16963605.html