根据位置着色单词

时间:2012-01-21 13:16:12

标签: java swing

我根据他们的位置给部分线条着色。

使用的库是Swing。 组件是JTextPane。

StyledDocument doc = editorJTextPane.getStyledDocument();

Style styleRed = editorJTextPane.addStyle("Red", null);
StyleConstants.setForeground(styleRed, Color.red);
StyleConstants.setBold(styleRed, rootPaneCheckingEnabled);

Style styleGreen = editorJTextPane.addStyle("Green", null);
StyleConstants.setForeground(styleGreen, Color.green);
StyleConstants.setBold(styleGreen, rootPaneCheckingEnabled);

String[] allLines = editorJTextPane.getText().split("\n");

int offSet1 = 0;
int offSet2 = 5;

for(int i=0; i<allLines.length; i++)
{
  line = allLines[i];
  lineLength = line.length() + 1;

  doc.setCharacterAttributes(offSet1, 4, editorJTextPane.getStyle("Red"), true);    

  doc.setCharacterAttributes(offSet2, 15, editorJTextPane.getStyle("Green"), true);

  offSet1 = offSet1 + lineLength;
  offSet2 = offSet2 + lineLength;
}

任何一条线,  doc.setCharacterAttributes(offSet1,4,editorJTextPane.getStyle(“Red”),true); 要么  doc.setCharacterAttributes(offSet2,15,editorJTextPane.getStyle(“Green”),true);

被评论,它正在发挥作用。两者都在那里,我收到错误, 线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException 在javax.swing.text.DefaultStyledDocument.setCharacterAttributes(DefaultStyledDocument.java:507)

喜欢知道setCharacterAttributes不应该在循环中吗?

由于

1 个答案:

答案 0 :(得分:0)

对于DefaultStyledDocument.java中的第507行,您必须使用JDK 7

public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) {
         .......
         AttributeSet sCopy = s.copyAttributes();//Line 507 here
         .......
     }

因此传入的AttributeSet为null。您发布的代码对我有用,因此您的代码必须在其他地方出错。

相关问题