addy
addy

Reputation: 385

Swing thread communication

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

Answers (2)

mre
mre

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

Related Questions