Swing/TabSize のバックアップの現在との差分(No.22)
- category: swing folder: TabSize title: JTextPaneでタブサイズを設定 tags: [JTextPane, StyledDocument, SimpleAttributeSet, TabSet, TabStop] author: aterai pubdate: 2005-04-25T00:01:26+09:00 description: JTextPaneのStyledDocumentが使用するパラグラフ属性として、タブストップが展開する文字数を設定します。 image:
概要
JTextPane
のStyledDocument
が使用するパラグラフ属性として、タブストップが展開する文字数を設定します。
Screenshot
Advertisement
サンプルコード
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 in GitHub: Java, Kotlin解説
上記のサンプルでは、JTextPane
からStyledDocument
を取得し、TabStop
から作成したTabSet
をパラグラフ属性として追加することでタブの幅を指定しています。
-
JTextArea
- JTextArea#setTabSize(int)メソッドでタブサイズの指定が可能
-
JTextPane
-
JTextPane
からStyledDocument
を取得し、TabStop
から作成したTabSet
をパラグラフ属性として追加することでタブの幅を指定
-
-
JTextArea
ではJTextArea#setTabSize(...)
メソッドでタブサイズの指定が可能 -
JTextPane
ではパラグラフ属性でタブサイズを指定する必要がある
参考リンク
- TabSet (Java Platform SE 8)
- Swing (Archive) - tabsize in JTextPane
- JTextPaneにTabSetを設定してTabStopの文字列揃えをテストする
- JTextFieldにタブ文字を挿入する