SetContentType ("text / html") for JTextPane does not work as expected

When you setContentType ("text / html"), it applies only to text that is set via JTextPane.setText (). All other text that fits in a JTextPane through styles is "immune" to the content type.

Here is what I mean:

private final String[] messages = {"first msg", "second msg <img src=\"file:src/test/2.png\"/> yeah", "<img src=\"file:src/test/2.png\"/> third msg"}; public TestGUI() throws BadLocationException { JTextPane textPane = new JTextPane(); textPane.setEditable(false); textPane.setContentType("text/html"); //Read all the messages StringBuilder text = new StringBuilder(); for (String msg : messages) { textext.append(msg).append("<br/>"); } textPane.setText(text.toString()); //Add new message StyledDocument styleDoc = textPane.getStyledDocument(); styleDoc.insertString(styleDoc.getLength(), messages[1], null); JScrollPane scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); //add scrollPane to the main window and launch //... } 

In general, I have a chat that is presented by JTextPane. I receive messages from the server, process them - set the color of the text for specific cases, change the smile markers to the image path, etc. Everything is done within HTML. But, as can be seen from the example above, only setText is a setContentType object ("text / html"), and the second part, where the newly added message is represented by "text / plain" (if I'm not mistaken).

Is it possible to apply the content type "text / html" to all the data that is inserted into the JTextPane? Without it, it is almost impossible to process messages without implementing a very complex algorithm.

+6
source share
3 answers

I do not think you should use the insertString () method to add text. I think you should use something like:

 JTextPane textPane = new JTextPane(); textPane.setContentType( "text/html" ); textPane.setEditable(false); HTMLDocument doc = (HTMLDocument)textPane.getDocument(); HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit(); String text = "<a href=\"abc\">hyperlink</a>"; editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null); 
+9
source

Recreate

Sorry, I misunderstood the problem: inserting a string as HTML. To do this, use the capabilities of HTMLEditorKit:

  StyledDocument styleDoc = textPane.getStyledDocument(); HTMLDocument doc = (HTMLDocument)styleDoc; Element last = doc.getParagraphElement(doc.getLength()); try { doc.insertBeforeEnd(last, messages[1] + "<br>"); } catch (BadLocationException ex) { } catch (IOException ex) { } 
+3
source

Here is a much simpler way to do this.

 JTextPane pane = new JTextPane(); pane.setContentType("text/html"); pane.setText("<html><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"); 
+1
source

All Articles