import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test {
static final int WIDTH = 200;
static final int HEIGHT = 300;
static JTextField l = new JTextField(20);
public static void main(String[] args) {
JFrame jf = new JFrame("測試程序");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
jf.setContentPane(contentPane);
JButton jb = new JButton("清空文本框中的信息");
contentPane.add(l, "North");
contentPane.add(jb, "South");
ActionListener ac = new ActionHandler(); // 創建一個事件監聽器
jb.addActionListener(ac); // 向事件源註冊
}
}
// 定義實現事件監聽類
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
new test().l.setText("");
}
}
將事件處理過程進行總結:
(1)定義事件事件監聽接口類:class ActionHandler implements ActionListener{ }
(2)創建事件監聽器:ActionListener ac = new ActionHandler();
(3)向源事件註冊:jb.addActionListener(ac);