简体   繁体   English

更改Java SWT标签时出现无效的线程访问错误

[英]Invalid Thread Access error when changing Java SWT Label

I want to run my program where the value of a label changes after the Timer goes off. 我想运行我的程序,其中计时器关闭后标签的值会更改。 But whenever the Timer runs I will keep getting the Invalid Thread access error and my label does not get updated. 但是每当计时器运行时,我都会不断收到无效线程访问错误,并且我的标签不会更新。

protected void createContents() {
    <--GUI codes -->

    //Timer set to go every 10 seconds
      ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              System.out.println("Timer");

              lblState.setText("On");
          }
      };
      new Timer(delay, taskPerformer).start();
}

This link from the SWT FAQ explains the error and how to solve it: any code that modifies GUI components (in your case, setting the text of the label) needs to run on the display thread, otherwise this error will occur. SWT FAQ中的此链接说明了错误及其解决方法:修改GUI组件的任何代码(在您的情况下,设置标签的文本)都需要在显示线程上运行,否则会发生此错误。

To run on the display thread, wrap the code inside a Runnable and call Display.getDefault().syncExec( with the provided Runnable : 要在显示线程上运行,请将代码包装在Runnable然后使用提供的Runnable调用Display.getDefault().syncExec(

Display.getDefault().syncExec(new Runnable() {
    public void run() {
        // code that affects the GUI
    }
});

All access to UI objects must be done in the user interface thread. 对UI对象的所有访问都必须在用户界面线程中完成。 You can do this using Display.asyncExec (or Display.syncExec ). 您可以使用Display.asyncExec (或Display.syncExec )执行此操作。

Change your line: 更改您的行:

lblState.setText("On");

to

Display.getDefault().asyncExec(() -> lblState.setText("On"));

for Java 8. For Java 7 or earlier use: 对于Java8。对于Java 7或更早版本,请使用:

Display.getDefault().asyncExec(new Runnable() {
   @Override
   public void run() 
   {
     lblState.setText("On");
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM