The file selector dialog box does not close

advertisements

Here is my code for file chooser dialog operation...

FileChooser fc = new FileChooser();
fc.setTitle("Pointel File");
File file1 = fc.showOpenDialog(MainFrame.objComponent.getPrimaryStage());

int i =0;
while(i < 90000){
System.out.println(i);
i++;
}

In the above code, the dialog is waiting until the 'while' loop completes execution rather than closing itself the moment we click 'open' button.

Am I missing something in the code which will close the dialog the moment we click the 'Open' or 'Cancel' button?
Can anyone please help me out?


You are doing a long running on your UI's Application Thread which should not be done, or else UI will become unresponsive.

Rather create a Task or Thread to do long running processes on application thread.

See this link for more on Concurrency in JavaFX

Here is a short example of Task:

import javafx.concurrent.Task;

....

FileChooser fc = new FileChooser();
fc.setTitle("Pointel File");
File file1 = fc.showOpenDialog(MainFrame.objComponent.getPrimaryStage());

    final Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int i = 0;
            while (i < 90000) {
                System.out.println(i);
                i++;
            }
            return null;
        }
    };
    Thread th = new Thread(task);
    th.setDaemon(true);
    th.start();

Also remember if you modify any JavaFX UI components wrap the code in Platform.runLater(Runnable r) block like this:

import javafx.concurrent.Task;

....

final Task task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        int i = 0;
        while (i < 90000) {
            System.out.println(i);
            i++;
        }
    Platform.runLater(new Runnable() {//updates ui on application thread
            @Override
            public void run() {
                //put any updates to ui here dont run the long running code in this block or the same will happen as doing a long running task on app thread
            }
        });
        return null;
    }
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();