大家肯定都知道在Eclipse中獲得當前活動的workbenchWindow可以采用如下的方式來完成。
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
或
(在Plugin類中)
getDefault().getWorkbench().getActiveWorkbenchWindow()
。一般情況下這兩個方式都能夠很好的工作。但是突然有一天發現他不能工作了。郁悶我都不行了。察看了一下變量(如下圖)。
這個activatedWindow明明有啊,怎么就取不到呢。
打開代碼一看,看到 org.eclipse.ui.internal.Workbench 類中的 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