【发布时间】:2017-03-09 00:08:06
【问题描述】:
问题:定期更新 GUI 字段时 SWT 冻结。
我想要一个基于 SWT 的带有文本字段的 GUI,值会定期递增。
- 最初我从单独的线程访问 textField 导致抛出异常:
线程“Thread-0”org.eclipse.swt.SWTException 中的异常:无效 org.eclipse.swt.SWT.error(SWT.java:4533) 处的线程访问 org.eclipse.swt.SWT.error(SWT.java:4448) 在 org.eclipse.swt.SWT.error(SWT.java:4419) 在 org.eclipse.swt.widgets.Widget.error(Widget.java:482) 在 org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:373) 在 org.eclipse.swt.widgets.Text.setText(Text.java:2311) 在 regreon.Incrementing.lambda$0(Incrementing.java:62) 在 java.lang.Thread.run(Thread.java:745)
-
阅读 SWT 文档后(感谢 @marko-topolnik) - 我尝试在循环中使用
display.SyncExec(Runnable r)或display.AsyncExec(Runnable r)和调用Thread.sleep的 runnable。但这导致整个事情都冻结了。 代码如下:打包任何东西; 导入 org.eclipse.swt.widgets.Display; 导入 org.eclipse.swt.widgets.Shell; 导入 org.eclipse.swt.widgets.Text; 导入 org.eclipse.swt.SWT;
公共类 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); }}
如何避免冻结和抛出异常?
【问题讨论】:
标签: java multithreading swt