对事件处理不太熟悉,ok,或许这篇博客对你有点帮助
package demo01;
import java.awt.event.*;
import javax.swing.*;
public class HandleEvent extends JFrame{ //HandleEvent 继承JFrame
public HandleEvent(){
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);
add(panel); //JFrame中包含panel ,panel中包含jbtOK
OKListenerClass listener1 = new OKListenerClass(); //实例化监听器listener1
CanelListenerClass listener2 = new CanelListenerClass();
jbtOK.addActionListener(listener1); //在jbtOK中添加监听器listener1
jbtCancel.addActionListener(listener2);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new HandleEvent();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class OKListenerClass implements ActionListener{ //OKListenerClass 实例ActionListener
public void actionPerformed(ActionEvent e){
System.out.println("OK button clicked");
}
}
class CanelListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("Canel button clicked");
}
}