我正在用 Java 制作一个文本编辑器用于培训目的。因此,我使用 JTextPane 编辑文本并使用 setCharacterAttributes 突出显示文本中的某些单词。该代码部分工作,在第一行中一切正常,但在第二行和前后代码停止工作。下面的代码显示了我修复此错误的尝试:
private void changeColor(StyledDocument styledDocument) { String keywords[] = {"html", "body", "div", "teste"}; String texto = edtEditing.getText(); int startIndex; int start; StyleContext context = StyleContext.getDefaultStyleContext(); Style styleDefault = context.getStyle(StyleContext.DEFAULT_STYLE); // default styledDocument.setCharacterAttributes(0, texto.length(), styleDefault, true); AttributeSet attr = context.addAttribute(context.getEmptySet(), StyleConstants.Foreground, Color.red); for (String word:keywords) { startIndex = 0; start = texto.indexOf(word, startIndex); while (start >= 0) { styledDocument.setCharacterAttributes(start, word.length(), attr, true); startIndex += word.length(); start = texto.indexOf(word, startIndex); } } }
请参阅下图中的错误: Click to see the error
错误似乎是由于 CRLF 而发生的,但我不明白为什么......
这是executable jar file 。只需选择"file"->“新建”并输入“teste” 提前致谢!
最佳答案
这个副作用是由这一行引起的:
String texto = edtEditing.getText();
您直接从 JTextPane
获取文本,但在 StyledDocument
对象上设置属性。将此行更改为:
StyledDocument document = edtEditing.getStyledDocument();
String texto = document.getText(0, document.getLength());
并处理可能出现的异常。
您可以运行下面的代码来查看此行为是否一致,并且与人们的预期相反,将打印“false”。
JTextPane pane = new JTextPane();
pane.setText("Something html\r\nSomething html");
StyledDocument document = pane.getStyledDocument();
String text2 = pane.getText();
String text1 = document.getText(0, document.getLength());
System.out.println(text1.equals(text2));
关于java - JTextPane仅在第一行正确设置字符属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919618/