所以我正在制作一个显示火车时间的小示例应用程序。现在JTable
显示火车的地方不是动态的。我想要的是,每次都要检查时间,30 secs or minute
并且桌子会消除“应该到达”的火车。然而,我被困在不断检查时间的部分。我创建了一个TimeChecker
在后台运行的类,但它并没有多大用处,因为当我将无限循环或线程放入我的JPanel
类时,用户界面不显示。
这是我的时间检查器:
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();
}
}