Java SWT的无效线程访问错误 [英] Invalid Thread Access Error with Java SWT

查看:122
本文介绍了Java SWT的无效线程访问错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我在Java中有一个简单的Java SWT应用程序,但是很奇怪的是,当我在侦听我自己的一个类触发的事件时尝试启动消息框/警报框时,出现一条错误消息,提示无效的线程使用权".

I have a simple Java SWT app in Java so far but the weird thing is when I try to launch a messagebox/alert box upon listening to an event fired by one of my own classes, I get an error saying "Invalid thread access".

主类触发并听到了我的类事件,但是这是当它必须显示MessageBox时出现无效线程访问"错误的时候.我试图在一个由所有其他将创建SWT GUI的代码组成的函数中显示MessageBox.该函数的外观如下:

My class event is fired and heard by the main class but it is when it has to show the MessageBox that the "Invalid thread access" error appear. I am trying to show the MessageBox in a function that consist of all the other codes that will create the SWT GUIs. This is how the function looks like:

public void createContents() {
    Shell shell = new Shell();
    //.....all the SWT GUI codes....
    MessageBox msg = new MessageBox(shell, SWT.OK);
    myClass.addEventListener(new MyClassEventClassListener() {
        @Override
        public void myClassEventHandler(MyClassEvent e) {
            msg.setText("Hello");
            msg.setMessage("Event fired!");
            int result = msg.open();
        }
    });
}

这些是类中的辅助功能.

These are the auxiliary functions together in the class.

<!-- language: lang-java -->
protected static Shell shell;
public static void main(String[] args) {
    MyClass new myClass = new MyClass();

    try {
        SWTApp window = new SWTApp();
        window.open();
    } catch (Exception e) {     
}

public void open() {
    Display display = Display.getDefault();
    createContents();
    shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

错误堆栈跟踪如下:

Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4083)
    at org.eclipse.swt.SWT.error(SWT.java:3998)
    at org.eclipse.swt.SWT.error(SWT.java:3969)
    at org.eclipse.swt.widgets.Display.error(Display.java:1249)
    at org.eclipse.swt.widgets.Display.checkDevice(Display.java:755)
    at org.eclipse.swt.widgets.Display.getShells(Display.java:2171)
    at org.eclipse.swt.widgets.Display.setModalDialog(Display.java:4463)
    at org.eclipse.swt.widgets.MessageBox.open(MessageBox.java:200)

任何帮助都会很棒. 谢谢!

Any help will be great. Thanks!

推荐答案

之所以抛出该错误,是因为您的侦听器代码是从SWT Display线程外部调用的.您可以像这样在显示线程上运行代码:

It is thrown because your listener code is called from outside the SWT Display thread. You run code on the display thread like this:

Display.getDefault().syncExec(new Runnable() {
    public void run() {
        // ...
    }
});

或异步:

Display.getDefault().asyncExec(new Runnable() {
    public void run() {
        // ...
    }
});

这篇关于Java SWT的无效线程访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆