我有一个对象列表(模型),不断地添加到其中(类似于日志文件),我想在 JEditorPane 中以富文本形式显示(视图)。如何将它们粘合在一起?
http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#document 看起来没有足够的信息可供使用。
DefaultStyledDocument
与 AttributeSet
一起使用:SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setBold(attr , true);
StyleConstants.setForeground(attr, Color.RED);
document.insertString(document.getLenght(),"yourstring", attr))
一个简单的解决方案是将模型中的每个对象转换为HTML并将字符串附加到一起,创建一个HTML文档,然后可以在JEditorPane上设置该文档。
好的,最简单的方法是扩展JTextPane。扩展类创建并管理底层列表。在格式更改(例如新颜色)时,列表会完全重新格式化数据。唯一的真正问题是自动滚动不是100%可靠的,两者都:
Container parent = getParent();
// get the parent until scroll pane is found
while (parent != null && !(parent instanceof JScrollPane)) {
parent = parent.getParent();
}
if (parent != null) {
JScrollPane scrollPane = (JScrollPane)parent;
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getMaximum());
}
并且
scrollRectToVisible(new Rectangle(0, getHeight() - 2, 1, 1));
有时文本窗格无法完全滚动,导致提供不一致的结果。
Abstract Document
是很痛苦的。最好使用一个中介模型,它监听您的Object
模型和文档(使用DocumentListener
),并根据需要更新模型或视图。如果您在用户时间内工作(而不是每秒更新Object
模型1000次),这种方法非常有效。