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

#download(https://lh3.googleusercontent.com/-eKfbGIGltkw/VeNSQCA5DkI/AAAAAAAAOAg/PyS8lMWBPu0/s800-Ic42/HonorDisplayProperties.png)

* サンプルコード [#c40aae77]
#code(link){{
editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
}}

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

- `body`タグのスタイルを表示するサンプルコード
-- [http://docs.oracle.com/javase/jp/8/docs/api/javax/swing/text/html/StyleSheet.html StyleSheet (Java Platform SE 8)]のサンプルを参考
-- ただし、`Style rule = styles.getStyle(name);`は、コンパイルできない(`Style rule = styles.getRule(name);`の間違い?)

#code{{
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) && rule instanceof AttributeSet) {
  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());
}}

* 参考リンク [#q7f13031]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JEditorPane.html#HONOR_DISPLAY_PROPERTIES JEditorPane.HONOR_DISPLAY_PROPERTIES (Java Platform SE 8)]

* コメント [#p16492a2]
#comment
#comment