Java Swing How to - Overwrite default font








Question

We would like to know how to overwrite default font.

Answer

//w ww  . ja va2s  .  com
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleContext;
import javax.swing.text.html.HTMLDocument;

public class Main {
  public static void main(String[] args) {
    String HTMLTEXT = "<html><head><style>.foot{color:red} .head{color:black}</style></head>"
        + "<span style='font-family:consolas'>java2s.com</span><br/>"
        + "<span style='font-family:tahoma'>java2s.com</span>";
    JTextPane textPane1 = new JTextPane();

    textPane1.setContentType("text/html");
    textPane1.setFont(new Font("courier new", Font.PLAIN, 32));
    textPane1.setDocument(new HTMLDocument() {
      @Override
      public Font getFont(AttributeSet attr) {
        StyleContext styles = (StyleContext) getAttributeContext();
        Font f = styles.getFont(attr);
        String ff = f.getFamily();
        System.out.println(ff);
        return textPane1.getFont();
      }
    });
    textPane1.setText(HTMLTEXT);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(textPane1));
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}