-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