我试图在 JEditorPane 的覆盖 DefaultStyledDocument(也提供自定义 EditorKit)中插入一个 LeafElement:但我得到一个 javax.swing.text.StateInvariantError。因此,按照JGuru 论坛主题的指导,我添加了 writeLock() 和 writeUnlock() 调用,但这次我的 JEditorPane 仍然为空。那么我应该如何覆盖 AbstractDocument 的 fireXXX() 方法,以便通知文档的所有侦听器?
这是我的主要课程:MyFrame.java
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class MyFrame extends JFrame {
public MyFrame(){
setSize(400, 300);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new MyEditorKit());
add(new JScrollPane(editorPane));
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
private static final long serialVersionUID = -2122161377842820073L;
}
这是我的班级 MyEditorKit.java
import javax.swing.text.Document;
import javax.swing.text.StyledEditorKit;
public class MyEditorKit extends StyledEditorKit {
@Override
public Document createDefaultDocument() {
return new MyDocument();
}
private static final long serialVersionUID = -5973765338689236766L;
}
我的班级 MyDocument.java
import javax.swing.JLabel;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class MyDocument extends DefaultStyledDocument {
public MyDocument(){
BranchElement rootElement = (BranchElement) getDefaultRootElement();
writeLock();
LeafElement black10Element = (LeafElement) createLeafElement(rootElement, new SimpleAttributeSet(),0, 1);
JLabel black10 = new JLabel("10 ...");
StyleConstants.setComponent(black10Element, black10);
writeUnlock();
}
private static final long serialVersionUID = -7424640574620960694L;
}
这是我用 writeLock() 和 writeUnlock() 注释行时的错误堆栈跟踪:
Exception in thread "main" javax.swing.text.StateInvariantError: Illegal cast to MutableAttributeSet
at javax.swing.text.AbstractDocument$AbstractElement.checkForIllegalCast(AbstractDocument.java:2050)
at javax.swing.text.AbstractDocument$AbstractElement.addAttributes(AbstractDocument.java:1983)
at javax.swing.text.AbstractDocument$AbstractElement.<init>(AbstractDocument.java:1777)
at javax.swing.text.AbstractDocument$LeafElement.<init>(AbstractDocument.java:2502)
at javax.swing.text.AbstractDocument.createLeafElement(AbstractDocument.java:1275)
at MyDocument.<init>(MyDocument.java:13)
at MyEditorKit.createDefaultDocument(MyEditorKit.java:9)
at javax.swing.JEditorPane.setEditorKit(JEditorPane.java:1058)
at MyFrame.<init>(MyFrame.java:11)
at MyFrame.main(MyFrame.java:16)
提前致谢。