---
title: "第四天：该实现个Editor玩玩了"
author: "eclipsesbs"
date: "2013-05-14T17:17:47Z"
tags: []
categories: ["编程语言"]
slug: "editor"
draft: false
lastmod: "2013-05-24T15:36:10Z"
id: 1869361
url: "https://eclipsesbs.iteye.com/blog/1869361"
---

作者：梁祺 （eclipsesbs@gmail.com)

 

来自：http://www.benisoft.net/day4/index.html

 

今天来看一下Editor，正如前面提到的，用户的大部分时间都会花在Editor上，Editor是用户主要完成任务的地方， 我们仍然使用Eclipse提供的模版，在创建Plug-in项目时，选择“Plug-in with an editor”模版。

![](http://www.benisoft.net/day4/day4A.png)

这个模版实现了一个XML编辑器，我们使用向导提供的缺省值，点击“Finish”。

![](http://www.benisoft.net/day4/day4B.png)

启动Eclipse，先创建一个项目，选择“File／New／Project”，然后选择“General／Project”， Project名为abc，点击”Finish“。然后选择“File／New／File”，在对话框里选择项目abc，文件名为abc.xml， 点击“Finish”。文件创建后，Eclipse有可能使用文本编辑器打开它，让我们先关闭abc.xml， 然后在Package Explorer View里，选中abc.xml，在右键菜单中选择“Open With／Sample XML Editor”， 这下，我们的XML Editor就工作了，我们尝试输入一段XML文本，属性值高亮为绿色，XML Editor工作正常。

![](http://www.benisoft.net/day4/day4G.png)

我们来看一下代码。打开plugin.xml，找到Plug-in Editor的Extensions子页， 可以看到这个例子扩展了扩展点”org.eclipse.ui.editors“，定义了一个editor。

- id：ID为“eclipse.tutorial.day4.editors.XMLEditor”
- name：名字为“Sample XML Editor”
- icon：图标为“sample.gif”
- extension：关联的文件扩展名为“xml”，也就是说，当Eclipse要打开一个文件扩展名为“xml”的文件时， 它会寻找相关的Editor来打开它，但是要注意，Eclipse允许多个Editor关联到同一个文件扩展名，这个时候， Eclipse会选取一个作为缺省Editor，如果用户指定过Editor，就象我们在前面所做的，选中文件， 并在右键菜单中选择“Open With／Sample XML Editor”，Eclipse就会记住这个Editor作为缺省Editor。 Eclipse也支持一个Editor关联多个文件扩展名，只要在这里用逗号分割它们就可以了。
- class：Editor的Java实现类。
- contributorClass：Editor Contributor的Java实现类。 Editor Contributor负责管理Editor的菜单栏，工具栏，和状态栏，比如往菜单栏和工具栏上添加Action。

![](http://www.benisoft.net/day4/day4H.png)

点击class，打开XMLEditor类。这个非常的简单，继承自TextEditor。 TextEditor是Eclipse提供的文本编辑器的Java实现类，它提供基本的文本编辑功能，包括剪切和粘贴。 既然XML文件也是文本文件，所以XMLEditor继承TextEditor也很自然。 这个例子的大部分代码都是和对XML文本的着色有关，这里我们就不花篇幅介绍了。

**public** **class** XMLEditor **extends** TextEditor {

    **private** ColorManager colorManager;

    **public** XMLEditor() {  
        **super**();  
        colorManager = **new** ColorManager();  
        setSourceViewerConfiguration(**new** XMLConfiguration(colorManager));  
        setDocumentProvider(**new** XMLDocumentProvider());  
    }  
    **public** **void** dispose() {  
        colorManager.dispose();  
        **super**.dispose();  
    }  
}

[Code Formatted by ToGoTutor](http://www.togotutor.com/code-to-html/java-to-html.php)

如果去看一下TextEditor的父类AbstractDecoratedTextEditor，我们就能够发现createPartControl()。 和View一样，Editor的UI控件的布局也是在这个方法里完成的。

如果希望从一个现有的Plug-in项目中新建Editor，在Plug-in Editor的Extensions页，点击”Add“按钮， 在对话框中输入”editors“，找到扩展点”org.eclipse.ui.editors“，并选中， 我们就会看到模板Editor和Multi-page Editor。同样，一般都会使用Editor来创建Editor的骨架， 删除掉不需要的代码。Multi-page Editor我们后面会介绍到，这里先略过。

到这里，我们了解了怎么创建一个Editor，创建Editor和View有一些类似，但是我们只演示了基本的步骤， 没有谈到如何为Editor和View提供输入，这需要结合更加接近实际的例子来说明。