在此感谢Java狂神说!!!
一、按钮和窗口的监听事件
package GUI;
import java.awt.*;
import java.awt.event.*;
public class TestDemo {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button("别点我");
MyActionListener1 myActionListener = new MyActionListener1();
button.addActionListener(myActionListener);
windowClose(frame);
frame.add(button);
frame.setBounds(100,100,200,200);
frame.setVisible(true);
}
static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
class MyActionListener1 implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("您点击了按钮!");
}
}
二.两个按钮可以共用一个监听
package GUI;
import java.awt.*;
import java.awt.event.*;
public class TestDemo {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new GridLayout(2,1));
Button button = new Button("别点我");
Button button1 = new Button("点我");
button.setActionCommand("别点我啊啊啊!");
MyActionListener1 myActionListener = new MyActionListener1();
button.addActionListener(myActionListener);
button1.addActionListener(myActionListener);
windowClose(frame);
frame.add(button);
frame.add(button1);
frame.setBounds(100,100,200,200);
frame.setVisible(true);
}
static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
class MyActionListener1 implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println(""+e.getActionCommand());
}
}