• title: JEditorPaneやJTextPaneに行間を設定する tags: [JEditorPane, JTextPane, StyledEditorKit] author: aterai pubdate: 2009-11-02T12:51:40+09:00 description: JEditorPaneやJTextPaneに行間を設定します。

概要

JEditorPaneJTextPaneに行間を設定します。

サンプルコード

class BottomInsetEditorKit extends StyledEditorKit {
  @Override public ViewFactory getViewFactory() {
    return new ViewFactory() {
      @Override public View create(Element elem) {
        String kind = elem.getName();
        if (kind != null) {
          if (kind.equals(AbstractDocument.ContentElementName)) {
            return new LabelView(elem);
          } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
            return new javax.swing.text.ParagraphView(elem) {
              @Override protected short getBottomInset() { return 5; }
            };
          } else if (kind.equals(AbstractDocument.SectionElementName)) {
            return new BoxView(elem, View.Y_AXIS);
          } else if (kind.equals(StyleConstants.ComponentElementName)) {
            return new ComponentView(elem);
          } else if (kind.equals(StyleConstants.IconElementName)) {
            return new IconView(elem);
          }
        }
        return new LabelView(elem);
      }
    };
  }
}
View in GitHub: Java, Kotlin

解説

  • 上: StyleConstants.setLineSpacingで、行間を指定したAttributeSetを作成し、JTextPane#setParagraphAttributesで設定しています。
    • フォントサイズ相対の行間になる
SimpleAttributeSet a = new SimpleAttributeSet();
StyleConstants.setLineSpacing(a, .5f);
//StyleConstants.setSpaceAbove(a, 5f);
//StyleConstants.setSpaceBelow(a, 5f);
//StyleConstants.setLeftIndent(a, 5f);
//StyleConstants.setRightIndent(a, 5f);
editor1.setParagraphAttributes(a, true);
setDummyText(editor1);
  • 下: ParagraphView#getBottomInsetをオーバーライドして、固定の行間をピクセルで指定しています。
    • フォントサイズに関係なく、アキ5px

StyleSheet styleSheet = new StyleSheet();
styleSheet.addRule("body {font-size: 24pt; line-height: 2.0}");
styleSheet.addRule(".test {margin-bottom: 2pt; padding-bottom: 1px; }");
//XXX: styleSheet.addRule("span {color: white; display:inline-block; margin-bottom: 10pt;}");
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
htmlEditorKit.setStyleSheet(styleSheet);
editor1.setEditorKit(htmlEditorKit);
editor1.setText("<html><body><div class='test'>12<br />a<br />n<font size='32'>123<br />sd</font></div></body></html>");

コメント