依處理器所掛的位置,總共有5種寫法,以計時器處理器為例, A.處理器掛在外部類別下:B.處理器掛在內部匿名類別下:
- 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");
- }
- }
C.處理器掛在內部有名類別下:
- 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();
- }
- }
D.處理器掛在本身類別下:
- 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");
- }
- }
- }
E.處理器同時掛在內部和外部類別下:
- 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();
- }
- }
- 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");
- }
- }
2008年5月28日 星期三
5 kinds of event handler styles
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言