• category: swing folder: HonorDisplayProperties title: JEditorPaneに設定したフォントをHTMLテキストに適用する tags: [JEditorPane, HTMLEditorKit, Font, StyleSheet, HTML] author: aterai pubdate: 2015-08-31T03:59:20+09:00 description: HTMLEditorKitでbodyタグにデフォルトで指定されている文字サイズではなく、JEditorPaneに設定したフォントをHTMLテキストで使用します。 image: https://lh3.googleusercontent.com/-eKfbGIGltkw/VeNSQCA5DkI/AAAAAAAAOAg/PyS8lMWBPu0/s800-Ic42/HonorDisplayProperties.png

概要

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)としてコンポーネントのデフォルトのフォントを使用するように設定する必要があります。

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();
  if ("body".equals(name)) {
    Style rule = styles.getStyle(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());

  • メモ:
    • JDK 1.8.0_60ではスクリーンショットのように自動的に折り返されるが、JDK 1.9.0-ea-b78では、水平スクロールバーが表示される?

参考リンク

コメント