2016-09-19 29 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