【问题标题】:Text editor with syntax highlighting and line numbers?带有语法高亮和行号的文本编辑器?
【发布时间】:2012-09-22 14:05:38
【问题描述】:

这对于一个团队项目来说有点挑战,更不用说单人实现了,但我试图使用JEditorPane 组合一个简单而优雅的带有语法突出显示的文本编辑器。我偶然发现了this,它已经停产,我很难理解里面的所有词法分析器文件和 .lex 的东西。我什至在一些博客中发现这个项目后来被其他团队接手,但又一次停止了。我不需要它太花哨,比如代码折叠和其他东西(即使我很想知道如何做到这一点),但我至少需要一个 basic syntax highlighting 存在并且在最左侧几乎有 行号,就像 Notepad++ 一样。请记住,我只需要它来突出显示 Java 源代码,至少现在是这样。

我要找的不是教程、文档齐全的示例和示例代码、预制包,甚至 NetBeans 工具都可以解决问题,我不需要从头开始编写源代码,我只需要一个可以使用的实现。提前致谢!

PS这不会是商业的或太大的,不要问我为什么要重新发明轮子,因为那里有这么多编程编辑器,我正在学习,这对我来说是一个很好的练习!

【问题讨论】:

  • 您在 Netbeans 周围看到过这个 tutorial 吗?或者你检查过这个秋千component
  • 第二个链接的示例甚至无法编译?第 27 行出错:找不到 org.jdesktop.swingx.JXEditorPane 的类!?
  • JXEditorPane 它是 SwingX 组件的一部分,也许你没有正确的依赖 swingx.java.net。对于教程,也许您应该阅读整个系列antonioshome.net/kitchen/netbeans

标签: java swing syntax-highlighting jeditorpane line-numbers


【解决方案1】:

RSyntaxTextArea 已获得 BSD 许可并支持您的要求,以及代码折叠等。使用非常简单。

【讨论】:

    【解决方案2】:

    嗯,我从事过一个类似的项目,这就是我想出的。就行号而言,我使用了附加到实际文本窗格的滚动窗格。然后滚动窗格使用以下代码更改数字:

    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();
    }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多