• title: JEditorPaneに設定したフォントをHTMLテキストに適用する tags: [JEditorPane, HTMLEditorKit, Font, StyleSheet, HTML] author: aterai pubdate: 2015-08-31T03:59:20+09:00 description: HTMLEditorKitでbodyタグにデフォルトで指定されている文字サイズではなく、JEditorPaneに設定したフォントをHTMLテキストで使用します。

概要

HTMLEditorKitbodyタグにデフォルトで指定されている文字サイズではなく、JEditorPaneに設定したフォントをHTMLテキストで使用します。

サンプルコード

editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
View in GitHub: Java, Kotlin

解説

HTMLEditorKitのデフォルトスタイルシートでは、bodyタグにfont-size: 14ptなどが設定されており、これがHTMLテキストのデフォルト文字サイズになっているため、JEditorPane#setFont(new Font("Serif", Font.PLAIN, 16))でフォントを指定しても反映されません。JEditorPaneに設定されたフォントを使用する場合は、JEditorPane#putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE)としてコンポーネントのデフォルトのフォントを使用するように設定する必要があります。

  • bodyタグのスタイルを表示するサンプルコード
    • StyleSheet (Java Platform SE 8)のサンプルを参考
    • ただし、Style rule = styles.getStyle(name);は、コンパイルできない(Style rule = styles.getRule(name);の間違い?)
StringBuilder buf = new StringBuilder(300);
HTMLEditorKit htmlEditorKit = (HTMLEditorKit) editor.getEditorKit();
StyleSheet styles = htmlEditorKit.getStyleSheet();
//System.out.println(styles);
Enumeration rules = styles.getStyleNames();
while (rules.hasMoreElements()) {
  String name = (String) rules.nextElement();
  Style rule = styles.getRule(name);
  if ("body".equals(name)) {
    Enumeration sets = rule.getAttributeNames();
    while (sets.hasMoreElements()) {
      Object n = sets.nextElement();
      buf.append(String.format("%s: %s<br />", n, rule.getAttribute(n)));
    }
  }
}
editor.setText(buf.toString());

参考リンク

コメント