Question

Here is the problem.

My main class implements SerialPortEventListener. After Serial event occurs, i have to check the String in a Text (i am using SWT API). Apparently, i can not reach text in a Text with Text.getText(), and get SWTException: Invalid thread access.

I tired to look here (Invalid Thread Access Error with Java SWT) and some other similar posts, but using this approach i get some other issues.

How can I access members of the UI to check their values?

Était-ce utile?

La solution

As already stated in the Exception Message: You are trying to access an UI-Element from a thread that differs from the Display-Thread.

I also stumbled across this several times when I was new to SWT.

You can avoid this issue by invoking the correct Thread, using:

        Display.getDefault().asyncExec(Runnable)

or

        Display.getDefault().syncExec(Runnable)

This way, you can define an anonymous runnable to access the needed information from your Text.

EDIT: Since you already knew about these methods on Display you now have to know how to return a value from that runnable, right? The solution to that depends on what you are going to do with these values. If its not a long-blocking operation, you could continue doing it inside the Display-Thread so you dont have to implement inter-thread-communication.

Otherwise you could use a Monitor-Object which your other thread waits on. If the Display-Thread (with the runnable) is then finished reading the Value of your Text, it can invoke notify on that Monitor (which can be any variable) so that your waiting Thread can continue.

EDIT2, since I can't comment:

MyRunnable runnable = new MyRunnable();
Display.getDefault().syncExec(runnable);

System.out.println(runnable.getText());


private class MyRunnable implements Runnable
{
    String myString;

    @Override
    public void run()
    {
       //Here you can also get the text from your Text-Object
        myString = "MyText";
    }

    String getText()
    {
        return myString;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top