JTextPaneでタブサイズを設定
Total: 10928
, Today: 2
, Yesterday: 2
Posted by aterai at
Last-modified:
概要
JTextPane
のStyledDocument
が使用するパラグラフ属性として、タブストップが展開する文字数を設定します。
サンプルコード
textpane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
FontMetrics fm = textpane.getFontMetrics(textpane.getFont());
int charWidth = fm.charWidth('m');
int tabLength = charWidth * 4;
TabStop[] tabs = new TabStop[10];
for (int j = 0; j < tabs.length; j++) {
tabs[j] = new TabStop((j + 1) * tabLength);
}
TabSet tabSet = new TabSet(tabs);
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setTabSet(attrs, tabSet);
int l = textpane.getDocument().getLength();
textpane.getStyledDocument().setParagraphAttributes(0, l, attrs, false);
view all解説
上記のサンプルでは、JTextPane
からStyledDocument
を取得し、TabStop
から作成したTabSet
をパラグラフ属性として追加することでタブの幅を指定しています。
JTextArea
ではJTextArea#setTabSize(...)
メソッドでタブサイズの指定が可能JTextPane
ではパラグラフ属性でタブサイズを指定する必要がある
参考リンク
- TabSet (Java Platform SE 8)
- Swing (Archive) - tabsize in JTextPane
- JTextPaneにTabSetを設定してTabStopの文字列揃えをテストする