Text editor with syntax highlighting and line numbers?

半腔热情 提交于 2019-12-03 03:34:38
bobby_light

RSyntaxTextArea is BSD licensed and supports your requirements, plus code folding and more. Very simple to use.

Well I worked on a similar project and here's what I came up with. As far the line numbers go I used a scrollpane attached to the actual textpane. The scrollpane was then changing numbers with the following code:

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

The syntax highlighting is not an easy task, but what I started with was being able to search for strings based off some text files that contained all keywords for a certain language. Basically based off the extension of a file the function would find the correct file and look for words in that file that were contained within the text area.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!