简体   繁体   English

Java Swing自定义文本JEditorPane

[英]Java Swing custom text JEditorPane

I have a list of Objects (the model) that are constantly appended to (similar to a log file) and I'd like to display as rich text in a JEditorPane (the view). 我有一个对象列表(模型)不断附加(类似于日志文件),我想在JEditorPane(视图)中显示为富文本。 How can I glue them together? 我怎么把它们粘在一起?

http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#document doesn't seem to give enough information to use. http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#document似乎没有提供足够的信息来使用。

一个简单的解决方案是将模型中的每个对象转换为HTML并附加字符串以创建可在JEditorPane上设置的HTML文档。

You can use DefaultStyledDocument together with AttributeSet : 您可以将DefaultStyledDocumentAttributeSet一起使用:

SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setBold(attr , true);
StyleConstants.setForeground(attr, Color.RED); 
document.insertString(document.getLenght(),"yourstring", attr))

Building a custom Abstract Document is painful. 构建自定义Abstract Document很痛苦。 You're better off with an intermediary model that listens to changes in both your Object Model and the document (with a DocumentListener ) and updates either the model or view, depending. 您最好使用中间模型来监听Object模型和文档(使用DocumentListener )中的更改,并根据需要更新模型或视图。 This works pretty well if you're working in user time (as opposed to updating the Object model 1,000 times per second). 如果您在用户时间工作(而不是每秒更新Object模型1,000次),这非常有效。

OK, so the simplest approach was to extend JTextPane. 好的,所以最简单的方法是扩展JTextPane。 The extended class created and managed the underlying list. 扩展类创建并管理基础列表。 On format change (eg new colours) the list completely reformats the data. 在格式更改(例如,新颜色)上,列表完全重新格式化数据。 The only real problem was that the auto-scrolling is not 100% reliable, Both: 唯一真正的问题是自动滚动不是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());
}

and

scrollRectToVisible(new Rectangle(0, getHeight() - 2, 1, 1));

Provide inconsistent results with the text pane sometimes not scrolling all the way. 提供不一致的结果与文本窗格有时不会一直滚动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM