邋遢居

我的Java天堂

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  61 Posts :: 2 Stories :: 90 Comments :: 0 Trackbacks

大家肯定都知道在Eclipse中获得当前活动的workbenchWindow可以采用如下的方式来完成。

PlatformUI.getWorkbench().getActiveWorkbenchWindow()

Plugin类中) getDefault().getWorkbench().getActiveWorkbenchWindow() 。一般情况下这两个方式能够很好的工作。但是突然有一天发现他不能工作了。郁闷我都不行了。察看了一下变量如下图display.jpg

这个activatedWindow明明有啊,怎么就取不到呢。

打开代码一看,看到 org.eclipse.ui.internal.Workbench 类中的 getActiveWorkbenchWindow 方法。

public  IWorkbenchWindow getActiveWorkbenchWindow() {
        
//  Return null if called from a non-UI thread.
        
//  This is not spec'ed behaviour and is misleading, however this is how
        
//  it
        
//  worked in 2.1 and we cannot change it now.
        
//  For more details, see [Bug 57384] [RCP] Main window not active on
        
//  startup
         if  (Display.getCurrent()  ==   null ) {
            
return   null ;
        }

        
//  Look at the current shell and up its parent
        
//  hierarchy for a workbench window.
        Control shell  =  display.getActiveShell();
        
while  (shell  !=   null ) {
            Object data 
=  shell.getData();
            
if  (data  instanceof  IWorkbenchWindow) {
                
return  (IWorkbenchWindow) data;
            }
            shell 
=  shell.getParent();
        }

        
//  Look for the window that was last known being
        
//  the active one
        WorkbenchWindow win  =  getActivatedWindow();
        
if  (win  !=   null ) {
            
return  win;
        }

        
//  Look at all the shells and pick the first one
        
//  that is a workbench window.
        Shell shells[]  =  display.getShells();
        
for  ( int  i  =   0 ; i  <  shells.length; i ++ ) {
            Object data 
=  shells[i].getData();
            
if  (data  instanceof  IWorkbenchWindow) {
                
return  (IWorkbenchWindow) data;
            }
        }

        
//  Can't find anything!
         return   null ;
    }

程序跑到 Display.getCurrent() 这一绝句就给我掉链子(返回了一个 null )。就是他,就是他了!到网上 google 了一下。看看在什么状况下他会返回一个 null. http://wiki.eclipse.org/index.php/FAQ_How_do_I_get_a_Display_instance%3F 找到了。

他说, Display 永远和创建他的线程联系在一起,并且一个线程拥有一个活动的 Display 。在创立 Display 的线程中可可以通过 Display.getCurrent() 获得当前活动的 Display 。如果出了这个线程就看不到这个 Display 了。如果有的线程不拥有 Display ,那它的 Display.getCurrent() 就只能得到 null 了。

回头看了一下我的代码,我是在新建的线程中启动了调用了这个方法。难怪他不给面子呢!


参考文献:

http://wiki.eclipse.org/index.php/FAQ_How_do_I_get_a_Display_instance%3F

http://help.eclipse.org/help31/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/Display.html

posted on 2006-12-04 15:01 Jet Geng 阅读(2612) 评论(0)  编辑  收藏 所属分类: Eclipse

只有注册用户登录后才能发表评论。


网站导航: