Problem: SWT freezes when GUI field is periodically updated.
I would like to have a SWT-based GUI with text field were values are periodically incremented.
- Initially I accessed textField from separate Thread what led to throwing exception:
Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:4533) at org.eclipse.swt.SWT.error(SWT.java:4448) at org.eclipse.swt.SWT.error(SWT.java:4419) at org.eclipse.swt.widgets.Widget.error(Widget.java:482) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:373) at org.eclipse.swt.widgets.Text.setText(Text.java:2311) at regreon.Incrementing.lambda$0(Incrementing.java:62) at java.lang.Thread.run(Thread.java:745)
After reading SWT documentation (thanks to @marko-topolnik ) - I tried using
display.SyncExec(Runnable r)
ordisplay.AsyncExec(Runnable r)
with runnable that calledThread.sleep
in the loop. But this caused the whole thing to freeze. Here is the code:package whatever; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.SWT;
public class FreezingGUI {
protected Shell shell; private Text text; public static void main(String[] args) { try { FreezingGUI window = new FreezingGUI(); window.open(); } catch (Exception e) { e.printStackTrace(); } } public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); // HOW TO DO THAT??? display.syncExec(() -> { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { Integer i = Integer.parseInt(text.getText()) + 1; text.setText(i.toString()); } } } ); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } protected void createContents() { shell = new Shell(); shell.setSize(450, 300); shell.setText("SWT Application"); text = new Text(shell, SWT.BORDER); text.setEditable(false); text.setText("0"); text.setBounds(30, 32, 78, 26); }
}
How to avoid freezing and throwing exception?