Reputation: 2814
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?
Upvotes: 2
Views: 1082
Reputation: 8865
Never do the GUI and the computational tasks on the same thread. Your UI should be running on one thread and your computational tasks should be on other threads. UI becomes unresponsive if they both are running on the same thread.
Firstly read about,
Using the Event Dispatch Thread
, you can dispatch your UI threads. Look at the answer given by @Erick Robertson related to EDT
.
Many posts available in SO about the above stated topics.
Upvotes: 0
Reputation: 36423
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();
Upvotes: 2