所以我正在制作一个显示火车时间的小示例应用程序。
现在,显示火车的 JTable
不是动态的。
我想要的是每 30 秒或分钟
检查一次时间,并且该表将消除“应该已经到达”的火车。
然而,我被困在不断检查的时间部分。我已经创建了一个在后台运行的 TimeChecker
类,但它没有多大用处,因为当我将无限循环或线程放入我的 JPanel
类时,用户界面没有不显示。
这是我的 TimeChecker:
package controller;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeChecker extends Thread {
private String timeStamp;
public String getTimeStamp() {
return timeStamp;
}
public void run() {
while(true) {
try {
Thread.sleep(2000);
String dateStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
timeStamp = dateStamp.substring(9,13);
System.out.println(timeStamp);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
这是我的面板类:
package view;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import controller.*;
public class Panel extends JPanel {
/* JPanel containing the JTabbedPane stuff */
JTabbedPane jtp = new JTabbedPane();
TimeChecker tc = new TimeChecker();
public Panel() {
super(new GridLayout(1,0));
Table t = new Table("Haymarket");
jtp.add(t);
jtp.setTitleAt(0, "Haymarket");
add(jtp);
tc.setDaemon(true);
tc.start();
}
public void addTrain(String d, String c, String dep, String a) {
/*
* Receives 4 parameters to control
* the new entry required for a train
*/
Table t = (Table) jtp.getComponentAt(jtp.getSelectedIndex());
t.addTrain(d,c,dep,a);
}
public void addStation(String s) {
/*
* Adds a station, after prompting the
* user for a station name
*/
jtp.add(new Table(s));
jtp.setTitleAt(jtp.getTabCount()-1, s);
jtp.setSelectedIndex(jtp.getTabCount()-1);
}
public void addStation(Table t) {
jtp.add(t);
jtp.setTitleAt(jtp.getTabCount()-1,t.getStation());
}
public void removeAllStations() {
jtp.removeAll();
}
public void removeStation() {
/*
* Removes currently selected station
*/
jtp.remove(jtp.getSelectedIndex());
}
public void removeTrain() {
/*
* WIP: Removes a train
*/
Table t = (Table) jtp.getComponentAt(jtp.getSelectedIndex());
t.removeTrain();
}
}
最佳答案
听起来你想要一个 javax.swing.Timer
每 30 秒触发一次。
或者,在后台线程中使用计时器(例如通过 ScheduledExecutorService
)- 然后获取信息,并且仅在您实际需要更新 UI 时才涉及 UI。
关于java - 不断检查时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18061731/