[英]Java FX GUI freezes
在我們學校的最新項目中,我遇到了一些問題。 我想觀察新條目的路徑,該路徑是由文件管理器按鈕選擇的,但是如果我選擇任何文件,則整個窗口都會凍結...我想它會因為調用“ observePath”方法而凍結,但我沒有不知道如何解決此問題。
這是代碼:
public void start() {
public Path absolutePath;
final Label labelSelectedDirectory = new Label();
Button btnOpenDirectoryChooser = new Button();
btnOpenDirectoryChooser.setText("Open DirectoryChooser");
btnOpenDirectoryChooser.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory =
directoryChooser.showDialog(primaryStage);
if(selectedDirectory == null) {
labelSelectedDirectory.setText("No Directory selected");
}else{
labelSelectedDirectory.setText(selectedDirectory.getAbsolutePath());
absolutePath = selectedDirectory.toPath();
try {
observePath();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
});
public void observePath() throws IOException, InterruptedException {
WatchService watcher = FileSystems.getDefault().newWatchService();
FileSystem fs = FileSystems.getDefault();
Path p = fs.getPath(absolutePath.toString());
WatchKey key = p.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
key = watcher.take();
for (WatchEvent event : key.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("found new data");
}
else {
System.out.println("no new data found");
}
}key.reset();
}
}
我希望有一個人可以幫助我。 非常感謝你
湯姆
如果observePath方法執行繁重的工作,則應在新線程中執行它。
new Thread( ()->{
observePath();
}).start();
事件處理程序在JavafxApplicationThread中執行,該程序負責更新UI。 您不應在此線程中執行任何長期任務,否則會遇到功能損失。
有關應用程序線程的更多信息,請參見此處。JavaFX應用程序線程如何工作?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.