0

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.

2

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help. I will try and see what I can accomplish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.