pixie
pixie

Reputation: 517

Java swing interface for algorithm

I am trying to build a Swing GUI for an algorithm I am developing. During its running, the algorithm will modify the GUI constantly. I have read that the long-running tasks should be separated from the GUI and that modifying the swing components should be done from the EDT thread. However, what I need is sort of an overlapping between these two: running the algorithm, the algorithm makes some changes, these changes must be reflected in the GUI, the algorithm continues its execution, makes another changes, which again must be reflected in the GUI and so on.

Could you give me some advice on what I should use to accomplish my objective?

Thank you in advance.

Upvotes: 0

Views: 319

Answers (1)

Raniz
Raniz

Reputation: 11123

You should use SwingUtilities.invokeLater for this:

public class MyAlgorithm {

    void doAlgorithm() {
        while(notDone()) {
            // Iterative work
            ...
            // Update the UI
            if(shouldUpdateUI()) {
                SwingUtilities.invokeLater(() -> {
                    // UI update code goes here
                });
            }
        }
    }
}

If you're not using Java 8, just replace the lambda (() -> { ... }) with a Runnable:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        // UI update code goes here
    }
});

Beware though that the UI will be updated on another thread so you may have to take a defensive copy of your state and update the UI based on that.

Upvotes: 2

Related Questions