TITLE:JEditorPaneのStyleSheetを使ってlist bulletを画像に変更

Posted by at 2012-12-10

JEditorPaneのStyleSheetを使ってlist bulletを画像に変更

`JEditorPaneHTMLEditorKitからStyleSheetを取得し、list-style-imageを使ってList bullet`を変更します。

  • &jnlp;
  • &jar;
  • &zip;
EditorPaneListStyle.png

サンプルコード

HTMLEditorKit htmlEditorKit = (HTMLEditorKit)pane.getEditorKit();
StyleSheet styleSheet = htmlEditorKit.getStyleSheet();
String u = getClass().getResource(bullet).toString();
styleSheet.addRule(String.format("ul{list-style-image:url(%s);margin:0px 20px;", u));
//styleSheet.addRule("ul{list-style-type:circle;margin:0px 20px;}");
//styleSheet.addRule("ul{list-style-type:disc;margin:0px 20px;}");
//styleSheet.addRule("ul{list-style-type:square;margin:0px 20px;}");
//styleSheet.addRule("ul{list-style-type:decimal;margin:0px 20px;}");
View in GitHub: Java, Kotlin

解説

  • 上: `Default`
  • 下: `ul{list-style-image:url(bullet.png);}`
    • `CSSlist-style-imageプロパティを使って、bullet`を画像に変更
    • `AlignmentY`が中心にならない?ので、画像の下に余白を追加
    • `ulのマージンもmargin:0px 20px;`に変更

  • `javax.swing.text.html.CSSは、list-style-typeプロパティも対応しているので、circle, square, decimalなどがbullet`として使用できるが、サイズは固定
    styleSheet.addRule("ul{list-style-type:circle;margin:0px 20px;}");
    //styleSheet.addRule("ul{list-style-type:disc;margin:0px 20px;}");
    //styleSheet.addRule("ul{list-style-type:square;margin:0px 20px;}");
    //styleSheet.addRule("ul{list-style-type:decimal;margin:0px 20px;}");
    

  • `javax.swing.text.html.CSSは、a:hoverなどの擬似クラス(pseudo-classes)や、:beforeなどの擬似要素(pseudo elements)に対応していないので、以下のようにlist-style-type:noneとして:beforeで任意の文字をbullet`に適用することができない
styleSheet.addRule("ul{list-style-type:none;margin:0px 20px;}");
styleSheet.addRule("ul li:before{content: "\u00BB";}");

  • `javax.swing.text.html.StyleSheet.ListPainter#drawShape(...)などをオーバーライドできれば直接bullet`の形やサイズを変更できそうだが、コンストラクタがパッケージプライベート

コメント