Java - change font in JTextPane containing HTML

I have a JTextPane and I have text inside this JTextPane. However, since I use HTML inside the panel, the text seems automatically changed to Times New Roman.

I am trying to set the font type in JTextPane with the default GUI font (JTextPane font when it is not HTML). However, I cannot just install the font on one font, because it is different from the operating system, so I want to find a way to get the default font, and then change the text that I have by default.

To demonstrate how text is replaced with Times New Roman during conversion, the following code is the format I used. How can I change it to achieve my goal?

import javax.swing.JFrame; import javax.swing.JTextPane; public class GUIExample { public static void main(String[] args) { JFrame frame = new JFrame("My App"); frame.setSize(300,300); JTextPane pane = new JTextPane(); pane.setContentType("text/html"); pane.setText("<html><b>This is some text!</b></html>"); frame.add(pane); frame.setVisible(true); } } 

Thanks!

+8
java swing jtextpane
source share
3 answers

The simplest way is probably something like this:

 string fontfamily = pane.getFont().getFamily(); 

This will give you the default font. Then just apply it using CSS:

 pane.setText("<html><body style=\"font-family: " + fontfamily + "\"<b>This is some text!</b></html>"); 
+7
source share

The following will do the trick:

  pane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); 

(Note that JTextPane continues with JEditorPane .)

Update (August 2016):

So that you can survive. Look, feel and change the system (for example, fonts changed in the Windows control panel), here you can place the line:

  @Override public void updateUI() { super.updateUI(); putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); } 

(This is also called at build time.)

+22
source share

JComponent html renderer uses its own font, not JComponent. To make the component render the same thing, you need to set the font attributes in the html line. Among other things, you need to set the font family, size, bold / italics, etc.

As an example, you can do the following:

 JTextPane pane = new JTextPane(); Font font = pane.getFont(); pane.setContentType("text/html"); pane.setText("<html><font face=\"" + font.getFamily() + "\" size=\"" + font.getSize() + "\"></font>This is some text!</html>"); 

It would be pretty trivial to create a function that does this for you. Pass it a JComponent and a string, and it will create you HTML text, including all font tags.

+1
source share

All Articles