简体   繁体   中英

Java SWT - best way to return data from components to other threads

I have a Java SWT app which runs a separate thread (other than the UI) for a connection to a chat server. If I want to update components of the UI from the connection thread, I can easily do this:

        myUIclass.MyShellReference.getDisplay().asyncExec(
               new Runnable() {
                 public void run(){
                     ... update some UI component

                 }
               }
        );

My Problem is I can't find a good way to GET data from components on the UI thread. An example would be trying to create a method in my connection thread to pull a String entered into a Text box on the UI Thread...

private String getTheText(){
    final String thetext;           
    myUIclass.MyShellReference.getDisplay().asyncExec(
        new Runnable() {
              public void run(){

                    // The below wont' work because thetext is final
                        // which is required in a nested class... blah!
                        thetext = myUIclass.getTextFromSomeTextBox();
            }
         }
     );
    return thetext;
}

The problem above is that I can't actually capture what is returned from the getTextFromSomeTextBox() method, because I can only use final variables which can't be assigned. The only other solution I know is using some Atomic reference object, but there has to be a better way as I'm sure people need to do this all the time.

Any help would be greatly appreciated!!!

You can use some transfer object for passing variables. Very stupid example which demonstrates the idea:

private String getTheText(){
    final String[] thetext = new String[1]; //very stupid solution, but good for demonstrating the idea

    myUIclass.MyShellReference.getDisplay().syncExec( //you should use sync exec here!
        new Runnable() {
              public void run(){

                    // The below wont' work because thetext is final
                        // which is required in a nested class... blah!
                        thetext[0] = myUIclass.getTextFromSomeTextBox();
            }
         }
     );
    return thetext[0];
}

Another way is to use callbacks or Future objects.

But in reality it kind of strange approach. I would normally pass values from UI thread to the other thread, since in UI thread we know exactly what's going on, and what kind of information we are giving outside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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