【发布时间】:2016-12-02 13:30:20
【问题描述】:
我正在尝试定期更新 FXML 中的 Google 地图标记。我尝试使用 Timer 和新的 Thread 来执行此操作,但其中任何一个都无法正常工作。
我用简单的任务测试了新的Thread,在我的用户界面中更新TextField,效果很好。
但是,当我使用我需要更新地图的实际代码时:
@FXML
public void handleTracking() throws IOException, InterruptedException {
new Thread() {
@Override
public void run() {
while (true) {
try {
double ar[] = FileImport.getGpsPosition();
System.out.println("Latitude: " + ar[0] + " Longitude: " + ar[1]);
double Ltd = ar[0];
double Lng = ar[1];
webEngine.executeScript(""
+ "window.lat = " + Ltd + ";"
+ "window.lon = " + Lng + ";"
+ "document.goToLocation(window.lat, window.lon);");
try {
Thread.sleep(555);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}.start();
}
我收到输出消息:
Exception in thread "Thread-26" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-26
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1216)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:980)
at de.fkfs.v2x.eval.FXMLDocumentController$1.run(FXMLDocumentController.java:84=)
当我使用计时器时会发生类似的事情,它适用于更新标签的任务,但是如果我尝试更新标记位置,它会抛出消息:
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
【问题讨论】:
-
您可以在此处找到从不同线程更新 UI 的示例:stackoverflow.com/documentation/javafx/2230/threading/7291/…
标签: multithreading google-maps javafx timer fxml