HTMLDocumentは、HTMLを保持するDocumentクラス。
JEditorPaneのコンテキストタイプに"text/html"を指定すると、JEditorPane内部で自動的に作られる。
メソッド | 概要 | |
---|---|---|
JEditorPane | getDocument() | JEditorPaneが保持しているHTMLDocumentを返す。 |
HTMLDocument | getLength() | ドキュメントの長さ(HTMLテキストの文字数?)を返す。 |
JEditorPane | getSelectionStart() | 選択されている文字列の先頭位置を返す。 選択されていない場合は、カーソルの位置。 |
JEditorPane | getSelectionEnd() | 選択されている文字列の末尾位置を返す。 選択されていない場合は、カーソルの位置。 |
JEditorPane | getSelectedText() | 選択されている文字列を返す。 |
HTMLDocument | getText(pos, len) | 指定された位置の文字列を返す。 |
HTMLDocument | getCharacterElement(pos) | posの位置が属するElementを返す。 |
HTMLDocument | getParagraphElement(pos) | posの位置が属するパラグラフ(段落)のElementを返す。 |
Element | getStartOffset() | そのElementの、ドキュメント内の開始位置を返す。 |
Element | getEndOffset() | そのElementの、ドキュメント内の終了位置を返す。 |
Element | getAttributes() | そのElementの属性を返す。 |
HTMLDocument | setCharacterAttributes(pos, len, attr, false); | 指定範囲の文字列の属性を変更する。 |
キャラクターエレメントは、属性が同じ文字列の塊り。
パラグラフエレメントは、たぶんpタグ1つ分。
HTML | <p>abc<b>def<i>ghi</i>jkl</b></p><p>mno</p> | ||||
キャラクター (属性) |
abc | def | ghi | jkl | mno |
b | b,i | b | |||
パラグラフ | abcdefghijkl | mno |
上記の例だと、bタグの中がiタグで2つに分かれているので、タグは2種類(b,i)だがエレメントは3つ(def,ghi,jkl)になる。
属性を変更するには、以下のようにする。
bold(太字)を入れ替える例:
/** * 太字を入れ替える * <p> * 先頭位置が太字なら通常にし、通常なら太字にする * </p> * @param doc * @param s 先頭位置 * @param e 終了位置 */ public static void changeBold(HTMLDocument doc, int s, int e) { Element el = doc.getCharacterElement(s); AttributeSet now = el.getAttributes(); SimpleAttributeSet chg = new SimpleAttributeSet(); if (StyleConstants.isBold(now)) { StyleConstants.setBold(chg, false); } else { StyleConstants.setBold(chg, true); } doc.setCharacterAttributes(s, e - s, chg, false); }
setCharacterAttributes()内部で新しいエレメントが構成されるし、画面も再描画される。