2016-09-19 30 views
-2

我試圖理解爲什麼這個程序不起作用。我是否正確使用actionlistener爲什麼它不顯示從線程運行時開始的時間,但線程沒有運行,我在屏幕上什麼都看不到。 我在做什麼錯,或者這是使用ActionListener類 的錯誤方式,或者我沒有正確使用它,下面是所有文件的代碼。我正在使用actionlistener

import java.awt.event.*; 
import java.util.TooManyListenersException; 

public class Timer extends Thread { 
    private int iTime = 0; 
    private ActionListener itsListener = null; 

    public Timer() { 
     super(); // allocates a new thread object 
     iTime = 0; // on creation of this object set the time to zero 
     itsListener = null; // on creation of this object set the actionlistener 
          // object to null reference 
    } 

    public synchronized void resetTime() { 
     iTime = 0; 
    } 

    public void addActionListener(ActionListener event) throws TooManyListenersException { 
     if (event == null) 
      itsListener = event; 
     else 
      throw new TooManyListenersException(); 
    } 

    public void removeActionListener(ActionListener event) { 
     if (itsListener == event) 
      itsListener = null; 
    } 

    public void run() { 

     while (true) { 
      try { 
       this.sleep(100); 
      } 
      catch (InterruptedException exception) { 
       // do nothing 
      } 
      iTime++; 

      if (itsListener != null) { 
       String timeString = new String(new Integer(iTime).toString()); 

       ActionEvent theEvent = new ActionEvent(this, 
         ActionEvent.ACTION_PERFORMED, timeString); 

       itsListener.actionPerformed(theEvent); 
      } 
     } 
    } 
} 

下一個文件

import java.awt.event.*; 
import java.util.TooManyListenersException; 

public class TextTimeDemonStration extends Object implements ActionListener { 
    private Timer aTimer = null; // null reference for this object 

    public TextTimeDemonStration() { 
     super(); 

     aTimer = new Timer(); 

     try { 
      aTimer.addActionListener(this); 
     } 
     catch (TooManyListenersException exception) { 
      // do nothing 
     } 

     aTimer.start(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     String theCommand = e.getActionCommand(); 

     int timeElapsed = Integer.parseInt(theCommand, 10); 

     if (timeElapsed < 10) { 
      System.out.println(timeElapsed); 
     } 
     else 
      System.exit(0); 
    } 
} 

的最後一個文件從

public class MainTest { 
    public static void main(String[] args) { 
     TextTimeDemonStration test = new TextTimeDemonStration();  
    }  
} 

回答

0

主類運行的程序在TextTimeDemonStration類,你叫aTimer.addActionListener(this);分配一個動作監聽

但在你的Timer.addActionListener()方法中,在if else塊,你寫

if (event == null) 
    itsListener = event; 
else 
    throw new TooManyListenersException(); 

由於this不爲空,它會拋出異常TooManyListenersException將被捕獲。

之後您啓動計時器。但是,由於itsListener在初始化後爲空,所以在您的Timer.run()方法中,將永遠不會執行if塊。因此,什麼都不做。

修正了邏輯Timer.addActionListener()方法,它應該工作得很好。

希望這會有所幫助。

+0

即時通訊不知道你是什麼意思我該如何解決它即時通訊新的Java現在我不明白你的意思你能告訴我一些代碼 – user2245494

+0

好吧我修好了謝謝你 – user2245494