好吧,我从事过一个类似的项目,这就是我想出的。就行号而言,我使用了附加到实际文本窗格的滚动窗格。然后滚动窗格使用以下代码更改数字:
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();
}
}
语法高亮不是一件容易的事,但我开始的目的是能够根据一些包含某种语言的所有关键字的文本文件来搜索字符串。基本上基于文件的扩展名,该函数将找到正确的文件并在该文件中查找包含在文本区域中的单词。