1
votes

I'm trying to 'append' an css/html table to a jtextpane.

When I do: setText like this:

        jtextpane.setText(css)

I get the desired result [perfect!]:

enter image description here

but when I try to append the text to the jtextpane like this:

        int len = jtextpane.getDocument().getLength();
        jtextpane.setCaretPosition(len); 
        jtextpane.replaceSelection(css);

I get the html code embedded like this: enter image description here

Q: how to append table's result (not the code) in the jtextPane? I assume I'm doing something wrong with the replaceSelection?! Thanks in advance

EDIT - additional information:

  • To append all text information to the jtextpane I'm using the following static method:
public static void appendToPane(JTextPane jtextpane, String userText, Color color)
{
  StyleContext sc = StyleContext.getDefaultStyleContext();
  AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
  aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Myriad Pro");
  aset = sc.addAttribute(aset, StyleConstants.FontSize, 20);
  int len = jtextpane.getDocument().getLength();
  jtextpane.setCaretPosition(len);
  jtextpane.setCharacterAttributes(aset, false);
  jtextpane.replaceSelection(userText);
}
  • on instantiation of the jtextpane I have:

    jtextpane.setContentType("text/html");

  • the original css string is this:

table.imagetable { font-family: verdana,arial,sans-serif; font-size:11px; color:#333333; border-width: 1px; border-color: #999999; border-collapse: collapse; } table.imagetable th { background:#b5cfd2 url('cell-blue.jpg'); border-width: 1px; padding: 8px; border-style: solid; border-color: #999999; } table.imagetable td { background:#dcddc0 url('cell-grey.jpg'); border-width: 1px; padding: 8px; border-style: solid; border-color: #999999; }

1
This likely depends on what was before it. Style tags have to go in the head of a document, if what you're appending to has closed head, then you may get problems. I don't know a lot about how Java renders HTML mind you. - Cruncher
If you could provide exactly what css is, and exactly what jtextpane.getText() is before the append, that would help - Cruncher
thanks @Cruncher, I just did. - adhg

1 Answers

1
votes

You have to declare what type of text you are using in the JTextPane

jtextPane.setContentType("text/html");

If this don't work, try also to include your text with correct <html> that should do. I had the same problem time ago, I am looking for a specific code.