带有语法高亮和行号的文本编辑器?

6
这可能是一个挑战,即使对于团队项目也很难,更别提一个人的实现了。但我想用JEditorPane制作一个简单而优雅的文本编辑器,并使用语法高亮。我偶然发现了这个,但它已经停止更新了,里面有许多词法分析文件和.lex文件,让我很难理解。我甚至在一些博客中发现,这个项目后来被其他团队接手,但最终也停止更新了。我并不需要它太花哨,例如具有代码折叠等功能(尽管我很想知道如何做到这一点),但我需要至少存在基本的语法高亮,并且类似于Notepad++的左侧有行号。请记住,我目前只需要它突出显示Java源代码。

我正在寻找的是教程、文档良好的示例和样例代码、预制包,甚至是NetBeans的工具都可以胜任,我不一定需要从头开始编写源代码,我只需要一个可以使用的实现。提前感谢您!

P.S.这不会是商业性质或太大的项目,请不要问为什么在有那么多编程编辑器的情况下我想要重新发明轮子,这对我来说是一个很好的练习!


你看到过这个Netbeans的教程吗?或者你检查了这个Swing 组件吗? - Nickmancol
第二个链接的示例甚至无法编译?第27行出现错误:找不到org.jdesktop.swingx.JXEditorPane的类! - Angelos Chalaris
JXEditorPane是SwingX组件的一部分,也许您没有正确的依赖关系http://swingx.java.net/。对于教程,也许您应该阅读整个系列http://www.antonioshome.net/kitchen/netbeans/。 - Nickmancol
2个回答

6

RSyntaxTextArea是BSD授权的,支持您的需求,还有代码折叠等功能。非常简单易用。


1

我曾经参与一个类似的项目,这是我的解决方案。关于行号,我使用了一个附加到实际文本窗格的滚动窗格。然后,使用以下代码来更改滚动窗格中的行号:

public class LineNumberingTextArea extends JTextArea
{
private JTextPane textArea;


/**
 * This is the contructor that creates the LinNumbering TextArea.
 *
 * @param textArea The textArea that we will be modifying to add the 
 * line numbers to it.
 */
public LineNumberingTextArea(JTextPane textArea)
{
    this.textArea = textArea;
    setBackground(Color.BLACK);
    textArea.setFont(new Font("Consolas", Font.BOLD, 14));
    setEditable(false);
}

/**
 * This method will update the line numbers.
 */
public void updateLineNumbers()
{
    String lineNumbersText = getLineNumbersText();
    setText(lineNumbersText);
}


/**
 * This method will set the line numbers to show up on the JTextPane.
 *
 * @return This method will return a String which will be added to the 
 * the lineNumbering area in the JTextPane.
 */
private String getLineNumbersText()
{
    int counter = 0;
    int caretPosition = textArea.getDocument().getLength();
    Element root = textArea.getDocument().getDefaultRootElement();
    StringBuilder lineNumbersTextBuilder = new StringBuilder();
    lineNumbersTextBuilder.append("1").append(System.lineSeparator());

    for (int elementIndex = 2; elementIndex < root.getElementIndex(caretPosition) +2; 
        elementIndex++)
    {
        lineNumbersTextBuilder.append(elementIndex).append(System.lineSeparator());
    }
    return lineNumbersTextBuilder.toString();
}
}

语法高亮并不是一项容易的任务,但我开始的时候能够基于一些包含某种语言所有关键字的文本文件搜索字符串。基本上,根据文件的扩展名,函数会找到正确的文件,并在该文件中查找包含在文本区域内的单词。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接