監聽事件-2022-12-7
阿新 • • 發佈:2022-12-07
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");
}
}
}
// 兩個按鈕公用一個監聽事件,不需要每個按鈕都寫一個事件,提高效率