我试图找到解决方案两天,仍然不知道该怎么办。如何在线程中为日历创建侦听器
这里的情况:我有哪里日历类型的变量通过无限循环做一些增量随时间(有一个源1的简化模型)运行的类。接下来我有一个GUI,在这里我开始新的线程(source 2)。
当一个变量'时间'发生变化时,我想进行一些数学计算并更改我的GUI上的一些标签。
据我所知,我应该创建PropertyChangeListener,这是一个地方,我有一个问题:我真的不明白该怎么做。我做了以下几件事:更新我的TimeLoop类到来源3。我创建了听众列表来源4(也简化了)。问题来了:我应该如何以及在哪里初始化侦听器?或者我错在哪里?感谢您的回答。
P.S.我唯一的想法是(来源5),这当然是行不通的。
源1(我的运行的类的一个例子):
public class TimeLoop implements Runnable {
private Calendar time = Calendar.getInstance();
@Override
public void run() {
try {
time.set(1997, 11, 27, 00, 00, 00);
while (true) {
time.add(time.HOUR, 1);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Interrupted error");
}
}
}
源2(源从我的GUI类):
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
Thread trTime = new Thread(new TimeLoop());
trTime.setName("TimeLoop");
trTime.start();
}
源3(编辑可运行类):
public class TimeLoop implements Runnable {
private Calendar time = Calendar.getInstance();
private PropertyChangeSupport support = new PropertyChangeSupport(this);
public void updateTime() {
Calendar oldValue = time;
time.add(time.HOUR, 1);
Calendar newValue = time;
support.firePropertyChange("time", oldValue, newValue);
}
public void addListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
@Override
public void run() {
try {
while (true) {
time.set(1997, 11, 27, 00, 00, 00);
updateTime();
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Interrupted error");
}
}
}
源4(监听):
public class TimeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent pce) {
System.out.println(pce.getPropertyName() + " has new value);
}
}
源5(错误代码):
public static void main(String args[]) {
Thread trTime = new Thread(new TimeLoop());
trTime.setName("TimeLoop");
trTime.start();
TimeLoop tLoop = new TimeLoop();
TimeListener tTistener = new TimeListener();
tLoop.addListener(tTistener);
}
Observer Patern真的很有用。最后,我的代码正在工作。非常感谢 :)。 – jexser