JEditorPaneに設定したフォントをHTMLテキストに適用する
Total: 5585, Today: 2, Yesterday: 2
Posted by aterai at
Last-modified:
Summary
HTMLEditorKitでbodyタグにデフォルトで指定されている文字サイズではなく、JEditorPaneに設定したフォントをHTMLテキストで使用します。
Screenshot

Advertisement
Source Code Examples
editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
View in GitHub: Java, KotlinDescription
HTMLEditorKitのデフォルトスタイルシートではbodyタグにfont-size: 14ptなどが設定されている- この設定が
HTMLテキストのデフォルト文字サイズになっているため、JEditorPaneにたとえばJEditorPane#setFont(new Font("Serif", Font.PLAIN, 16))とフォントを変更しても反映されない
- この設定が
JEditorPaneに設定されたフォントを使用する場合は、JEditorPane#putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE)としてコンポーネントのデフォルトのフォントを使用するように設定する必要がある
bodyタグのスタイルを表示するサンプルコード- StyleSheet (Java Platform SE 8)のサンプル(
ShowStyles)を参考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());
- StyleSheet (Java Platform SE 8)のサンプル(