[英]How to invoke method in main thread from thread that is used as WatchService?
當事件從具有WatchService的其他線程觸發時,需要調用在主類中定義的redraw()
方法。 如何使其運作?
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
List < String > args = getParameters().getRaw();
Runnable watchFileChangesThread = () -> {
try {
setUpWatchService();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
new Thread(watchFileChangesThread).start();
//...
}
private void redraw(){//redraw UI}
private void setUpWatchService() throws IOException, InterruptedException {
final Path path = FileSystems.getDefault().getPath(System.getProperty("user.dir"), "");
System.out.println(path);
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent < ? > event : wk.pollEvents()) {
final Path changed = (Path) event.context();
System.out.println(changed);
if (changed.endsWith("input.txt")) {
System.out.println("My file has changed");
}
}
// reset the key
boolean valid = wk.reset();
if (!valid) {
System.out.println("Key has been unregistered");
}
}
}
}
}
調用Platform.runLater(this::redraw);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.