views:

1319

answers:

4

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). 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.

+2  A: 

One simple solution would be to convert each object in the model to HTML and append the strings to create an HTML document that can be set on the JEditorPane.

Mark
Yes, this would be the simplest solution but I wanted to rerender the data when a user wished to change their color scheme or filter the data. I guess the whole data could be re-appended after any event.
Pool
If that is the case I think you might be better using a JTable. It would be easier to make a TableModel for your objects than try to make a Document. You could then apply filters to your table model and change table renederer settings for color etc.
Mark
A: 

Building a custom Abstract Document is painful. 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. This works pretty well if you're working in user time (as opposed to updating the Object model 1,000 times per second).

Mike Katz
The way I understand it - models for Editor Panes must be Documents. If you do not implement Document how can your custom model be added?
Pool
I meant to use one of the standard StyleDocuments and just manipulate text and and attributes.
Mike Katz
+2  A: 

You can use DefaultStyledDocument together with AttributeSet:

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

OK, so the simplest approach was to extend 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:

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.

Pool