我正在尝试在RCP应用程序中创建一个最初不可见的标签。当我单击“保存”按钮时,它变为可见。同样,它应该在5秒内不可见。
为此,我写了以下代码:
saveButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
// TODO Auto-generated method stub
System.out.println(textName.getText());
String text = textName.getText();
tree.getSelection()[0].setText(text);
String nodeId = ((TreeStructure) tree.getSelection()[0]
.getData()).getNodeId();
// update the database
UpdateTree updateTree = new UpdateTree();
updateTree.renameNode(text, nodeId);
label.setBounds(xForFirstButton, yIndexForButtons
+ Constants.BUTTON_BUFFER, Constants.BUTTON_WIDTH,
Constants.BUTTON_HEIGHT);
label.setVisible(true);
AbstractAction myAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
label.setVisible(false);
}
};
Timer myTimer = new Timer(5000, myAction);
myTimer.start();
}
但是,这段代码在运行时会出现以下错误:
Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4441)
at org.eclipse.swt.SWT.error(SWT.java:4356)
at org.eclipse.swt.SWT.error(SWT.java:4327)
at org.eclipse.swt.widgets.Widget.error(Widget.java:476)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:367)
at org.eclipse.swt.widgets.Control.setVisible(Control.java:3781)
at com.app.editor.views.EditorView$2$1.actionPerformed(EditorView.java:183)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
可以请任何人指出问题是什么?
提前致谢!
答案 0 :(得分:4)
更改UI的所有代码必须在UI线程中运行 - Timer
正在不同的线程中运行代码。
而不是Timer
使用:
Display.getDefault().timerExec(milliseconds, runnable);
答案 1 :(得分:0)
要从一个不是ui线程的线程更新ui,你必须使用它:
Display.getDefault().syncExec(new Runnable() {
public void run() {
// Update UI here
}
});
syncExec
将在您的rcp应用程序的ui线程中执行您的操作。
这类似于Swing中的invokeLater()
方法。