简体   繁体   中英

Java FX GUI freezes

in our latest project in school, I got some problems. I want to observe a Path for new entries, the path is chosen by a file director button but if I choose any file, the whole window freezes... I guess it got frozen as the "observePath" method got called but I don't know how to fix this problem.

Here's the code:

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();
        }

    }

I hope someone can help me. Thank you very much

Tom

If your observePath method does heavy work you should execute it in a new Thread.

new Thread( ()->{
 observePath();
}).start();

Event handlers are executed in the JavafxApplicationThread which is responsible for updating the UI. You should not do any long lasting tasks in this thread or else you'll experience functionality loss.

More info in regards to the application thread can be found here How JavaFX application thread works?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM