-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();
}
}
即时通讯不知道你是什么意思我该如何解决它即时通讯新的Java现在我不明白你的意思你能告诉我一些代码 – user2245494
好吧我修好了谢谢你 – user2245494