依處理器所掛的位置,總共有5種寫法,以計時器處理器為例, A.處理器掛在外部類別下:import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerTest1 { public static void main(String args[]) throws Exception { ActionListener al = new TimerHandler(); Timer t = new Timer(1000,al); t.start(); Thread.sleep(10000); t.stop(); } } class TimerHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事1"); } }B.處理器掛在內部匿名類別下:import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerTest2 { public static void main(String args[]) throws Exception { ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事2"); } }; Timer t = new Timer(1000,al); t.start(); Thread.sleep(10000); t.stop(); } }C.處理器掛在內部有名類別下:import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerTest3 { public static void main(String args[]) throws Exception { new TimerTest3(); } TimerTest3() throws Exception { ActionListener al = new TimerHandler(); Timer t = new Timer(1000,al); t.start(); Thread.sleep(10000); t.stop(); } private class TimerHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事3"); } } }D.處理器掛在本身類別下:import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerTest4 implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事4"); } public static void main(String args[]) throws Exception { ActionListener al = new TimerTest4(); Timer t = new Timer(1000,al); t.start(); Thread.sleep(10000); t.stop(); } }E.處理器同時掛在內部和外部類別下:import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerTest5 { public static void main(String args[]) throws Exception { ActionListener al = new ActionAdapter() { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事5x"); } }; Timer t = new Timer(1000,al); t.start(); Thread.sleep(10000); t.stop(); } } class ActionAdapter implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("執行每次叫醒要作的事5"); } }
5 kinds of event handler styles
訂閱:
文章 (Atom)
Disable UDP to solve frequent RDP disconnection
解決 RDP 遠端桌面經常斷線問題:「關閉 UDP 傳輸」 在使用 Windows 內建的 遠端桌面(RDP, Remote Desktop Protocol) 連線時,你是否也常遇到連線突然卡死、畫面凍結,或是頻繁跳出「連線已中...