• title: JEditorPaneで改行を表示 tags: [JEditorPane, StyledEditorKit] author: aterai pubdate: 2007-06-11 description: JEditorPaneで改行記号を表示します。

概要

JEditorPaneで改行記号を表示します。Swing - JTextPane View Problemから、ソースコードの大部分を引用しています。

サンプルコード

class MyEditorKit extends StyledEditorKit {
  @Override public ViewFactory getViewFactory() {
    return new MyViewFactory();
  }
}

class MyViewFactory implements 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 MyParagraphView(elem);
      } 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);
  }
}

class MyParagraphView extends ParagraphView {
  private static final Color pc = new Color(120, 130, 110);
  public MyParagraphView(Element elem) {
    super(elem);
  }
  @Override public void paint(Graphics g, Shape allocation) {
    super.paint(g, allocation);
    paintCustomParagraph(g, allocation);
  }
  private void paintCustomParagraph(Graphics g, Shape a) {
    try {
      Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
      Rectangle r = (paragraph == null) ? a.getBounds() : paragraph.getBounds();
      int x = r.x;
      int y = r.y;
      int h = r.height;
      Color old = g.getColor();
      g.setColor(pc);
      //paragraph mark
      g.drawLine(x + 1, y + h / 2, x + 1, y + h - 4);
      g.drawLine(x + 2, y + h / 2, x + 2, y + h - 5);
      g.drawLine(x + 3, y + h - 6, x + 3, y + h - 6);
      g.setColor(old);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
View in GitHub: Java, Kotlin

解説

StyledEditorKitを継承するEditorKitを作成し、これをJEditorPane#setEditorKitメソッドで、JEditorPaneに設定しています。

このEditorKitは、Elementが段落(AbstractDocument.ParagraphElementName)の場合、独自の改行記号を追加で描画するViewを返すViewFactoryを生成しています。

参考リンク

コメント