我创建了SwingWorker
实例,并在此实例的worker thread(tAccess = new TimeAccess()).execute())
中安排它以访问时间。但是我需要另一个swing worker实例来持续访问数据库。这该怎么做?
// when execute both instances ,sometimes GUI become unresponsive.
tAccess = new TimeAccess()).execute();
dAccess = new DataAccess()).execute();
代码:
public class DataAccess extends SwingWorker<Void, ArrayList<TimeTable>> {
@Override
protected Void doInBackground() throws SQLException, ClassNotFoundException {
int timeRun = 0;
ArrayList<TimeTable> timeList = null;
while (timeRun == 0) {
timeList = TimeTableController.viewTimeTable();
publish(timeList);
}
return null;
}
@Override
protected void process(List<ArrayList<TimeTable>> dataList) {
ArrayList<TimeTable> timeArray = dataList.get(dataList.size() - 1);
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
int x = 0;
for (TimeTable time : timeArray) {
dtm.setValueAt(time.getCity() + " " + time.getTime(), x, 0);
dtm.setValueAt(time.getCity() + " " + time.getTime(), x, 1);
x = x + 1;
// System.out.println(x);
System.out.println(javax.swing.SwingUtilities.isEventDispatchThread() + "database thread chkr");
}
}
}
private class TimeAccess extends SwingWorker<Void, String> {
@Override
protected Void doInBackground() {
int timeRun = 0;
while (timeRun == 0) {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));
String timeNow = sdf.format(cal.getTime());
publish(timeNow);
}
return null;
}
@Override
protected void process(List<String> timeList) {
String time = timeList.get(timeList.size() - 1);
clockLabel.setText(time);
System.out.println(javax.swing.SwingUtilities.isEventDispatchThread());
}
}
答案 0 :(得分:3)
问题似乎是你在这里有一个无限循环:
while (timeRun == 0) {
调用一些方法:
TimeTableController.viewTimeTable();
我将假设此方法不会阻止,或者任何合理的方法。所以:
publish
;然后这显然占用了EDT的所有时间 - 试图跟上你要求的更新。
所以,使用SwingWorker
做得很好。更多地考虑你的逻辑。