当事件从具有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");
}
}
}
}
}
答案 0 :(得分:1)
致电Platform.runLater(this::redraw);