今天向大家介紹Eclipse中很有用的一個功能: Link with Editor。
當打開很多文件,而左邊的Navigator又有很多資源,很深層次時, 找到當前的編輯器對應的是哪個項目的那個文件,是一件困難的事情。
Link with Editot自動在Navigator中定位資源,並選中, 如下圖所示,雙向箭頭就是Link with Editor未選中時:
啓用後,選中右邊的java文件,左邊也會自動選中相應的文件:
這個功能是如何實現的呢?
查看ResourceNavigator的editorActivated方法,可以看到實現代碼。
protected void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled()) {
return;
}
IFile file = ResourceUtil.getFile(editor.getEditorInput());
if (file != null) {
ISelection newSelection = new StructuredSelection(file);
if (getTreeViewer().getSelection().equals(newSelection)) {
getTreeViewer().getTree().showSelection();
} else {
getTreeViewer().setSelection(newSelection, true);
}
}
}
當Link with Editor啓用後,程序會獲得當前編輯器的文件, 並在左邊的Navigator樹形結構裏選中。
我們可以繼承ResourceNavigator並對代碼做一些修改,做一個自己的Navigator: 比如選中編輯器時,選中左邊對應的父文件夾。
只需修改一句代碼:
ISelection newSelection = new StructuredSelection(file.getParent());
本文介紹了 Link with Editor功能,實現原理,以及如何做一個定製的。
注:在最新的Eclipse中,類ResourceNavigator已經棄用
【完】