TITLE:JEditorPaneで改行を表示
#navi(../)
*JEditorPaneで改行を表示 [#l76cb974]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-06-11~
更新日:&lastmod;

#contents

**概要 [#r217a724]
JEditorPaneで改行記号を表示します。[[JTextPane View Problem>http://forum.java.sun.com/thread.jspa?threadID=5122980]]から、ソースコードの大部分を引用しています。

#screenshot

**サンプルコード [#r8bfcb2e]
#code{{
class MyEditorKit extends StyledEditorKit {
  public ViewFactory getViewFactory() {
    return new MyViewFactory();
  }
}

class MyViewFactory implements ViewFactory {
  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);
  }
  public void paint(Graphics g, Shape allocation) {
    super.paint(g, allocation);
    paintCustomParagraph(g, allocation);
  }
  public void paintCustomParagraph(Graphics g, Shape a) {
    try {
      Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
      int y = a.getBounds().y;
      int x = (paragraph==null)?a.getBounds().x:paragraph.getBounds().x;
      int z = a.getBounds().height / 2;
      Color old = g.getColor();
      g.setColor(pc);
      g.drawLine(x+1, y+z, x+1, y+a.getBounds().height-4);
      g.drawLine(x+2, y+z, x+2, y+a.getBounds().height-5);
      g.drawLine(x+3, y+a.getBounds().height-6, x+3, y+a.getBounds().height-6);
      g.setColor(old);
    }catch(Exception e) { e.printStackTrace(); }
  }
}
}}
-&jnlp;
-&jar;
-&zip;

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

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

**参考リンク [#vccc314a]
-[[JTextPane View Problem>http://forum.java.sun.com/thread.jspa?threadID=5122980]]

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