事件监听
- 事件监听:当某个事情发生时,干什么?
- 当按下按钮,在控制台输出aaaaa
- 当按下X,关闭窗口
package com.yuecheng.lesson01;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.BreakIterator;
public class A1 {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
frame.setSize(500,500);
Button button = new Button("玥骋说:");
A2 a2 = new A2();
button.addActionListener(a2);
frame.add(button, BorderLayout.NORTH);
windowclose(frame);
}
private static void windowclose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class A2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("肖婉茹大笨蛋");
}
}
两个按钮共享一个事件
package com.yuecheng.lesson01;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class A3 {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new GridLayout(2,1));
Button button = new Button("xiao");
Button button2 = new Button("wan");
A4 a4 = new A4();
button2.addActionListener(a4);
button.addActionListener(a4);
button2.setActionCommand("肖婉茹说");
frame.add(button);
frame.add(button2);
frame.pack();
frame.setVisible(true);
frame.setBounds(0,0,500,500);
}
}
class A4 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand()+"她爱我");
}
}