Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Change font in a JTextPane containing HTML

I have a JTextPane and I have some text within that JTextPane. However, because I have been using HTML within the Pane, the text seems to have been automatically changed to Times New Roman.

I'm trying to set the font type within the JTextPane to the default font of the GUI (the font of the JTextPane when it's not HTML). However I can't just set the font to one font because it differs from operating system, therefore I want to find a way to get the default font and then change the text I have to the default font.

To demonstrate how the text is swapped to Times New Roman when converted, the following code is the format I have used. How could 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!

like image 440
mino Avatar asked Feb 17 '12 21:02

mino


1 Answers

The following will do the trick:

 pane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);

(Note that JTextPane extends JEditorPane.)

Update (Aug 2016):

For the setting to survive Look & Feel and system changes (e.g. Fonts changed in the Windows Control Panel) the line can be placed here:

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

(This is also called during construction.)

like image 109
Luke Usherwood Avatar answered Oct 22 '22 07:10

Luke Usherwood