事件监听
package com. dong. lesson02 ;
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 TestActionEvent {
public static void main ( String [ ] args) {
Frame frame = new Frame ( ) ;
Button button = new Button ( ) ;
MyActionListener myActionListener = new MyActionListener ( ) ;
button. addActionListener ( myActionListener) ;
frame. setSize ( 400 , 400 ) ;
frame. add ( button, BorderLayout . CENTER) ;
frame. setVisible ( true ) ;
frame. pack ( ) ;
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 ( "yyds!" ) ;
}
}
package com. dong. lesson02 ;
import java. awt. * ;
import java. awt. event. ActionEvent ;
import java. awt. event. ActionListener ;
public class TestActionTwo {
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 ) ;
frame. pack ( ) ;
}
}
class MyMonitor implements ActionListener {
@Override
public void actionPerformed ( ActionEvent e) {
System . out. println ( "按钮被点击了:msg==>" + e. getActionCommand ( ) ) ;
if ( e. getActionCommand ( ) . equals ( "start" ) ) {
}
}
}