Swing/ParagraphMark のバックアップの現在との差分(No.14)
- category: swing folder: ParagraphMark title: JEditorPaneで改行を表示 tags: [JEditorPane, StyledEditorKit] author: aterai pubdate: 2007-06-11T17:28:09+09:00 description: JEditorPaneのパラグラフ終了位置に改行を意味する図形を追加表示します。 image:
概要
JEditorPane
のパラグラフ終了位置に改行を意味する図形を追加表示します。Swing - JTextPane View Problemから、ソースコードの大部分を引用しています。
Screenshot
Advertisement
サンプルコード
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);
return new ParagraphWithEopmView(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);
}
}
#spandel
class MyParagraphView extends ParagraphView {
#spanend
#spanadd
class ParagraphWithEopmView extends ParagraphView {
#spanend
private static final Color pc = new Color(120, 130, 110);
public MyParagraphView(Element elem) {
public ParagraphWithEopmView(Element elem) {
super(elem);
}
#spanadd
#spanend
@Override public void paint(Graphics g, Shape allocation) {
super.paint(g, allocation);
paintCustomParagraph(g, allocation);
}
#spanadd
#spanend
private void paintCustomParagraph(Graphics g, Shape a) {
try {
Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
Rectangle r = (paragraph == null) ? a.getBounds() : paragraph.getBounds();
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;
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(MARK_COLOR);
//paragraph mark
// paragraph mark
g2.drawLine(x + 1, y + h / 2, x + 1, y + h - 4);
g2.drawLine(x + 2, y + h / 2, x + 2, y + h - 5);
g2.drawLine(x + 3, y + h - 6, x + 3, y + h - 6);
g2.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
}
View in GitHub: Java, Kotlin解説
StyledEditorKit
を継承するEditorKit
を作成し、これをJEditorPane#setEditorKit
メソッドで、JEditorPane
に設定しています。
-
StyledEditorKit
を継承するEditorKit
を作成し、これをJEditorPane#setEditorKit
メソッドでJEditorPane
に設定 - この
EditorKit
はElement
がパラグラフ(AbstractDocument.ParagraphElementName
)の場合、改行記号を末尾に追加で描画するView
を返すViewFactory
を生成
EditorKit
は、Element
がパラグラフ(AbstractDocument.ParagraphElementName
)の場合、改行記号を末尾に追加で描画するView
を返すViewFactory
を生成します。