Skip to content

Use SwingWorker for Safe Async UI Modification#14756

Closed
johannes-wolf wants to merge 1 commit intomagefree:masterfrom
johannes-wolf:fix-battlefield-async-panel-access
Closed

Use SwingWorker for Safe Async UI Modification#14756
johannes-wolf wants to merge 1 commit intomagefree:masterfrom
johannes-wolf:fix-battlefield-async-panel-access

Conversation

@johannes-wolf
Copy link
Copy Markdown
Contributor

@johannes-wolf johannes-wolf commented Apr 16, 2026

It is not allowed to modify UI in a raw Thread, so we must use SwingWorker for async operations that modify the UI on completion (https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html).

This could potentially fix some of the UI bugs/crashes.

(Second fix in doClick seems only used by tests but should also not use Thread.)

this.jPanel.remove(mageCard);
});
t.start();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SwingUtilities.invokeLater instead?

Copy link
Copy Markdown
Contributor Author

@johannes-wolf johannes-wolf Apr 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With SwingWorker, Plugins.instance.onRemoveCard(mageCard, count); runs on a non-Swing thread, but the done() callback gets called on the EDT. So I guess, for this scenario SwingWorker might be better, as it does not block the EDT.

But I can change it to SwingUtilities.invokeLater if you want to.

@JayDi85
Copy link
Copy Markdown
Member

JayDi85 commented Apr 16, 2026

Yes, it’s important to modify GUI in swing thread only, e.g. on gui events/methods. If some game code must modify GUI/component like card then it must modify data only or call it inside a swing thread like PR example with invokelater. All that exceptions with miss/null inner component are related to that restricted gui modification from other threads.

@JayDi85
Copy link
Copy Markdown
Member

JayDi85 commented Apr 16, 2026

There is a helper method to find such use cases: ThreadUtils. ensureRunInGUISwingThread

IMG_2205

@johannes-wolf johannes-wolf force-pushed the fix-battlefield-async-panel-access branch from 915e898 to f519458 Compare April 16, 2026 22:01
@johannes-wolf
Copy link
Copy Markdown
Contributor Author

Closed. I will provide a better fix in a new PR.

@johannes-wolf johannes-wolf deleted the fix-battlefield-async-panel-access branch April 16, 2026 23:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants