ActionListener動作事件監聽器,當你在點擊按鈕時希望可以實現一個操作就得用到該接口了。
ActionListener接口所在包
ActionListener接口在event包中,即在開頭引入該包。
1 import java.awt.event.*;
ActionListener接口使用方法
該接口只用實現一個方法叫做actionPerformed(ActionEvent arg0)這個方法。這個方法就是你希望觸發事件時程序要做什么。
1 class ButtonListener/*自定義名字*/ implements ActionListener { 2 public void actionPerformed(ActionEvent arg0) { 3 /*content*/ 4 } 5 }
為該按鈕添加對象:
1 ButtonListener button_listener = new ButtonListener(); 2 button.addActionListener(button_listener);
接下來如果你又想移除該對象了,就直接remove掉就行了
1 button.removeActionListener(button_listener);
代碼演示:
1 package Example; 2 import java.awt.*; 3 import java.awt.event.*; 4 import javax.swing.*; 5 6 public class example3 extends JFrame { 7 //final static long serialVersionUID = 1L; 8 Container container = getContentPane(); 9 JButton button = new JButton("點擊我");//定義按鈕類 10 11 class ButtonListener implements ActionListener { 12 int x = 0; 13 14 public void actionPerformed(ActionEvent arg0) { 15 example3.this.button.setText("我被點擊了" + (++x) + "次"); 16 example3.this.button.setFont(new Font("宋體",Font.PLAIN,25)); 17 } 18 } 19 20 public example3() 21 { 22 super("JFrame窗體"); 23 this.setBounds(200, 100, 500, 500); 24 button.addActionListener(new ButtonListener()); 25 container.add(button); 26 this.setVisible(true); 27 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 28 } 29 30 public static void main(String[] args) 31 { 32 new example3(); 33 } 34 }
輸出截圖: