1. 程式人生 > >eclipse rcp 解決自定義編輯器editor重複開啟的問題

eclipse rcp 解決自定義編輯器editor重複開啟的問題

參考部落格:https://blog.csdn.net/linuxchyu/article/details/16984737

在eclipse rcp程式設計中,我們經常會自定義編輯器用於開啟自定義的檔案,會遇到每次雙擊檔案都開啟編輯器的問題,如何解決這個問題呢,我所知道的有兩種方法:

方法一:重寫Editor對應的IEditorInput中的equals方法,確保Editor的唯一性

	@Override
	public boolean equals(Object obj) {
		if(null == obj) 
			return false;
		if(!(obj instanceof TopologyEditorInput)) 
			return false;
		if(!getName().equals(((TopologyEditorInput)obj).getName())) 
			return false;
		return true;
	}

這個方法可以解決雙擊檔案開啟編譯器的問題,但是我發現在新建檔案時預設開啟編譯器後,在此雙擊檔案也會開啟編輯器,所以這個方法不太完美

方法二:重寫Editor對應的IEditorInput中的equals方法,確保Editor的唯一性

在org.eclipse.ui.editors擴充套件點中有個matchingStrategy的元素,可以實現IEditorMatchingStrategy介面,重寫public boolean matches(IEditorReference editorRef, IEditorInput input)方法,就可以做到判斷編輯器輸入是否匹配開啟的編輯器。 

程式碼如下:

//解決編輯器不重複開啟的方法
public class DiagramMatchingStrategy implements IEditorMatchingStrategy {

	@Override
	public boolean matches(IEditorReference editorRef, IEditorInput input) {
		// TODO Auto-generated method stub
		try {
			final IFile newDataFile = (IFile)input.getAdapter(IFile.class);
			final IFile openEditorDataFile = (IFile) editorRef.getEditorInput().getAdapter(IFile.class);

			if (null != newDataFile && newDataFile.equals(openEditorDataFile)) {
				return true;
			}
		} catch (PartInitException exception) {
			exception.printStackTrace();
		}

		return new DiagramMatchingStrategy().matches(editorRef, input);
	}

}