2012-02-03 29 views
0

我有一个Java SWT应用程序,它运行与聊天服务器连接的单独线程(UI除外)。如果我想更新从连接线的UI组件,我可以很容易地做到这一点:Java SWT - 从组件向其他线程返回数据的最佳方式

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

       } 
       } 
     ); 

我的问题是我无法找到从UI线程上的组​​件GET数据的好办法。一个例子是想在我的连接线拉订立UI线程文本框中的字符串,创建方法......

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; 
} 

上面的问题是,我无法真正捕捉返回什么从getTextFromSomeTextBox()方法中,因为我只能使用不能分配的最终变量。我知道的唯一的其他解决方案是使用一些Atomic参考对象,但必须有更好的方法,因为我确信人们总是需要这样做。

任何帮助将不胜感激!

+0

最终变量可以分配,但只能分配一次。 – 2012-02-03 00:12:09

回答

3

您可以使用一些传递对象来传递变量。这表明这个想法非常愚蠢例如:

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]; 
} 

另一种方法是使用回调或Future对象。

但实际上它有点奇怪的做法。我通常会将UI线程的值传递给另一个线程,因为在UI线程中,我们知道到底发生了什么,以及我们在外部提供了什么样的信息。

相关问题