关键字加亮显示
SUN_DEMON (sudemon@163.com) www.egemmer.cn, www.gemsuit.cn
eclipce文本编辑器的关键字能够加亮显示, 作者对这个功能很感兴趣, 在学习之余做了一个示例代码.
本示例使用Java编写.
写代码之前
- 你必须理解StyleDocument怎么改变字体的样式.
- StyleContext怎么添加新的样式.
- DocumentListener监视器.
开始编写
清单1 keywords.properties
# @(#) Depict: key code.
#
# Author: SUN_DEMON
#
# Date:
07
5
4

# java keyword
java_keywords
=
import
null
package
try
catch
finally
final
for
do
while
int
double
long
boolean
byte
void
public
protected
private
native
short
float
char
class
return
continue
break
if
else
switch
this
case
implements
interface
static
new
extends
abstract
super
# C Sharp keyword
csharp_keywords
=
abstract
as base bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event explicit extern
false
finally
fixed
float
for
foreach
goto
if
implicit in
int
interface
internal is lock
long
namespace
new
null
object operator out override params
private
protected
public
readonly ref
return
sbyte sealed
short
sizeof stackalloc
static
string struct
switch
this
throw
true
try
typeof uint ulong unchecked unsafe ushort using virtual
void
volatile
while
清单2 CodeStyle
package
org.sy.styleeditor.style;

import
java.util.HashSet;
import
java.util.ResourceBundle;
import
java.awt.Color;
import
java.util.StringTokenizer;

import
javax.swing.text.BadLocationException;
import
javax.swing.text.Style;
import
javax.swing.text.StyleConstants;
import
javax.swing.text.StyleContext;
import
javax.swing.text.StyledDocument;


/** */
/**
* <p>
*
* </p>
*
* @author SUN_DEMON
* @date 2007-5-4
* @project styleeditor
*/

public
abstract
class
CodeStyle
...
{

// 资源名称
private static final String BASENAME = "org.sy.styleeditor.style.resources.keywords";

// 划定界限
private static final String DELIM = "(); {}. ";

// 资源界限
private static final String RESOURCES_DELIM = " ";

// 字体
private static final String FAMILY = "Courier New";

// 字体大小
private static final int SIZE = 12;

// 关键字颜色
private static final Color KEYWORDS_FOREGROUND = new Color(51, 102, 153);

// 默认字体颜色
private static final Color DEFAULT_FORGROUND = new Color(0, 0, 0);

// 样式上下文
private static final StyleContext styleContext = new StyleContext();

// 资源
private static final ResourceBundle resources = ResourceBundle
.getBundle(BASENAME);

// 关键字集合
private static final HashSet<String> keywords = new HashSet<String>();


public CodeStyle(String key) ...{
// 添加默认样式
addStyle("none");
// 添加关键字样式
addStyle("keywords", KEYWORDS_FOREGROUND);
// 添加所有关键字
StringTokenizer tokenize = new StringTokenizer(getResourceString(key),
RESOURCES_DELIM);
while (tokenize.hasMoreTokens())
keywords.add(tokenize.nextToken());
}


/** *//**
* 将text填充文本到doc中.
*
* @param text -
* 要填充到StyledDocument中的文本
* @param doc -
* 填充的StyledDocument对象
*/

public void markStyle(String text, StyledDocument doc) ...{

try ...{
StringTokenizer tokenize = new StringTokenizer(text, DELIM, true);

while (tokenize.hasMoreTokens()) ...{
String str = tokenize.nextToken();
Style s = keywords.contains(str.trim()) ? styleContext
.getStyle("keywords") : styleContext.getStyle("none");
doc.insertString(doc.getLength(), str, s);
}

} catch (BadLocationException e) ...{
e.printStackTrace();
}
}


protected void addStyle(String key) ...{
addStyle(key, DEFAULT_FORGROUND, SIZE, FAMILY);
}


protected void addStyle(String key, Color color) ...{
addStyle(key, color, SIZE, FAMILY);
}


protected void addStyle(String key, Color color, int size, String fam) ...{
Style s = styleContext.addStyle(key, null);
if (color != null)
StyleConstants.setForeground(s, color);
if (size > 0)
StyleConstants.setFontSize(s, size);
if (fam != null)
StyleConstants.setFontFamily(s, fam);
}


/** *//**
* 从此资源包或它的某个父包中获取给定键的字符串。
*
* @param key -
* 所需字符串的键
* @return 给定键的字符串
*/

protected String getResourceString(String key) ...{
return resources.getString(key);
}
}
清单3 JavaCodeStyle
package
org.sy.styleeditor.style;


public
class
JavaCodeStyle
extends
CodeStyle
...
{

private static final String JAVA_KEYWORDS = "java_keywords";


public JavaCodeStyle() ...{
super(JAVA_KEYWORDS);
}
}
清单4 CSharpCodeStyle
package
org.sy.styleeditor.style;


public
class
CSharpCodeStyle
extends
CodeStyle
...
{

private static final String CSHARP_KEYWORDS = "csharp_keywords";


public CSharpCodeStyle() ...{
super(CSHARP_KEYWORDS);
}
}
清单5 StyleEditor
package
org.sy.styleeditor;

import
javax.swing.JTextPane;
import
javax.swing.event.DocumentEvent;
import
javax.swing.event.DocumentListener;
import
javax.swing.text.BadLocationException;
import
javax.swing.text.DefaultStyledDocument;
import
javax.swing.text.StyledDocument;

import
org.sy.styleeditor.style.CodeStyle;
import
org.sy.styleeditor.style.JavaCodeStyle;


/** */
/**
* <p>
*
* </p>
*
* @author demon
* @project styleeditor
* @date 2007-5-4
*/

public
class
StyleEditor
extends
JTextPane
implements
DocumentListener
...
{

private static final long serialVersionUID = 1L;

private CodeStyle codeStyle = new JavaCodeStyle();


public StyleEditor() ...{
setDocument(new DefaultStyledDocument());
getDocument().addDocumentListener(this);
}


public void changedUpdate(DocumentEvent e) ...{
}


public void insertUpdate(DocumentEvent e) ...{
update();
}


public void removeUpdate(DocumentEvent e) ...{
update();
}


private void update() ...{
StyledDocument oDoc = getStyledDocument();
StyledDocument nDoc = new DefaultStyledDocument();

try ...{
String text = oDoc.getText(0, oDoc.getLength());
codeStyle.markStyle(text, nDoc);

oDoc.removeDocumentListener(this);
nDoc.addDocumentListener(this);

int off = getCaretPosition();
setDocument(nDoc);
setCaretPosition(off);

} catch (BadLocationException e) ...{
e.printStackTrace();

} finally ...{
oDoc = null;
}
}
}
清单6 Runner
package
org.sy.styleeditor.run;

import
java.awt.BorderLayout;

import
javax.swing.JFrame;
import
javax.swing.JScrollPane;

import
org.sy.styleeditor.StyleEditor;


public
class
Runner
...
{


public static void main(String[] args) ...{
JFrame app = new JFrame(TITLE);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(WITDH, HEIGHT);
app.add(new JScrollPane(new StyleEditor()), BorderLayout.CENTER);
app.setVisible(true);
}

private static final int WITDH = 600, HEIGHT = 400;

private static final String TITLE = "Java关键字加亮显示文本编辑器(作者:孙跃 日期:2007/5/4)";

}
运行 Runner 类.
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>