Reputation: 385
I am creating a small swing application which plots a set of points given in a file. Guidelines suggested me to invoke a new thread for the GUI, for which I used the following code.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new View().setVisible(true);
}
});
One of the scenario in the application is to open a file (which is done using a JFileChooser
).
private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
//some heavy operations
} else {
System.out.println("File access cancelled by user.");
}
}
There are some heavy operations that are needed to be done, before proceeding to plot the points.
My questions are, is it advisable to place heavy codes in the GUI
thread ? Is it possible to send the file object to the main thread for processing and send the results to GUI
thread ?
Please note that I have no idea about Java Threading API.
Upvotes: 2
Views: 714
Reputation: 20751
use SwingWorker
SwingWorker
proposes a way to solve it by performing the time-consuming task on another background thread, keeping the GUI responsive during this time.
take a look at this
http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
http://www.theeggeadventure.com/wikimedia/index.php/SwingWorker_Example
http://www.javaworld.com/javaworld/jw-06-2003/jw-0606-swingworker.html
Upvotes: 4
Reputation: 44250
If the result of the long running task modifies a Swing component, you can use SwingWorker
. For more information, please see Worker Threads and SwingWorker.
Upvotes: 1