Java学习-GUI编程-事件监听
public class TestActionEvent {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button("aaa");
MyActionListener mal = new MyActionListener();
button.addActionListener(mal);
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//关闭窗口
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");
}
}
点击按钮,输出’aaa’。
监听多个事件
public class TestAction2 {
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);
windowClose(frame);
}
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//多个按钮只写一个监听类,可以用if-else判断触发了哪个事件
System.out.println("按钮被点击了,msg:"+e.getActionCommand());
}
}
先点击start,后点击stop。