14

Basically, I have a JTextPane to hold some text which I wish to style. JTextArea would have been better for me to use but I'm told you cannot style the text in these?

However, the JTextPane doesn't seem to style properly. For example, the following code is just returned with the HTML included:

public static void main(String[] args) {
    JFrame j = new JFrame("Hello!");
    j.setSize(200,200);
    JTextPane k = new JTextPane();
    k.setText("<html><strong>Hey!</strong></html>");
    j.add(k);
    j.setVisible(true);
}

I want to be able to just style some text in a JTextPane when a user interacts with the interface, but so far, it just returns the string with the HTML still in! Help!

om-nom-nom
  • 60,231
  • 11
  • 174
  • 223
mino
  • 6,340
  • 21
  • 55
  • 72

3 Answers3

21

If you want to diplaying Html contents in the JTextPane then you have to set for JTextPane#setContentType("text/html");, example here

EDIT:

for JEditorPanes / JTextPanes is there another way by implements StyledDocument, MutableAttributeSet and with customized Highlighter, example here

a.m. way is without using Html syntax

Community
  • 1
  • 1
mKorbel
  • 108,320
  • 17
  • 126
  • 296
6

Let Java know it will be HTML using setContentType method.

k.setContentType("text/html"); 
RanRag
  • 43,987
  • 34
  • 102
  • 155
3

I use a Look and Feel (Substance) and calling setContentType("text/html") has problems with the font displayed. I solved it by calling:

textPane.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

Another option is wrapping the HTML text in a JLabel. Following your example the code is:

JTextPane k = new JTextPane();
k.insertComponent(new JLabel("<html><strong>Hey!</strong></html>"));
IvanRF
  • 6,305
  • 5
  • 43
  • 66
  • Using `JTextArea` is often better than using `JLabel` because `JTextArea` scrolls better in a `JScrollPane` and allows the user to select and copy the text. Thanks for the info about Substance Look and Feel. I use it also so that tip was helpful. – Enwired Aug 24 '16 at 22:18