所以我的代碼工作,可能不是最漂亮或最有效的,但現在它完成工作。然而,我的問題是爲什麼我需要某些偏移值,比如我在某些函數的地方有+ 1,而行編號有+2。這些神奇的數字有點令人困惑,因爲它們使程序工作爲需要,但他們爲什麼要這樣做?我將這些加到了總數上,我明白了他們爲什麼會工作,但仍然沒有對這些神奇數字的具體解釋。如果你能告訴我他們的表現會很棒。以下是一些可供參考的代碼。爲什麼我們需要一個抵消值
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();
}
}
public void goToLine(JTextPane text)
{
String lineToSearch = JOptionPane.showInputDialog(null, "Line Number: ");
int total = 0;
int lineNum = 0;
for (String line : text.getText().split("\n"))
{
lineNum +=1;
String lineNumStr = lineNum + "";
if (lineNumStr.compareTo(lineToSearch) == 0)
{
if(line == null)
{
text.setCaretPosition(total);
}
text.setCaretPosition(total);
break;
}
total += line.length() + 1;
}
}
public void search(JTextPane text)
{
Document myText = text.getDocument();
final StyleContext cont = StyleContext.getDefaultStyleContext();
final AttributeSet reset = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.GREEN);
String wordToSearch = JOptionPane.showInputDialog(null, "Word to search for:");
Highlighter highlighter = text.getHighlighter();
highlighter.removeAllHighlights();
HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
int m;
int total = 0;
for (String line : text.getText().split("\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
total += line.length() + 1;
}
continue;
}
try
{
highlighter.addHighlight(total + m, total + m + wordToSearch.length(), painter);
}catch(BadLocationException ex)
{}
while(true)
{
m = line.indexOf(wordToSearch, m + 1);
if (m == -1)
{
break;
}
try{
highlighter.addHighlight(total + m, total + m + wordToSearch.length(), painter);
}catch(BadLocationException e)
{
}
}
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
total += line.length() + 1;
}
continue;
}
try
{
myText.insertString(total,"", reset);
}
catch(BadLocationException ex)
{
}
}
當然,行號編號基本上在文本窗格的左側顯示行號。搜索將突出顯示要搜索的單詞,轉到行將轉到指定的行。 –
'if(line == null)'語句應該做什麼?這似乎是設置一個插針位置,它將設置爲相同的東西 – khelwood
是的,我認爲這可能有點多餘,當我試圖做出一些工作 –