• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextPaneでタブサイズを設定
#navi(../)
*JTextPaneでタブサイズを設定 [#bc0a9823]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-04-25~
更新日:&lastmod;
---
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: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTUxfmvVtI/AAAAAAAAAmk/hIXOEpGYKYw/s800/TabSize.png
---
* 概要 [#summary]
`JTextPane`の`StyledDocument`が使用するパラグラフ属性として、タブストップが展開する文字数を設定します。

#contents
**概要 [#sf0e9788]
JTextPaneでタブサイズを設定します。[[Java Forums - tabsize in JTextPane>http://forum.java.sun.com/thread.jspa?forumID=57&threadID=285096]]からの引用です。
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTUxfmvVtI/AAAAAAAAAmk/hIXOEpGYKYw/s800/TabSize.png)

#screenshot
* サンプルコード [#sourcecode]
#code(link){{
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);
}}

**サンプルコード [#f20b0404]
 textpane.setFont(new Font("monospaced", Font.PLAIN, 12));
 FontMetrics fm = textpane.getFontMetrics(textpane.getFont());
 int charWidth = fm.charWidth('m');
 int tabWidth = charWidth * 4;
 TabStop[] tabs = new TabStop[10];
 for(int j=0;j<tabs.length;j++) {
   tabs[j] = new TabStop((j+1)*tabWidth);
 }
 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);
* 解説 [#explanation]
- `JTextArea`
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTextArea.html#setTabSize-int- JTextArea#setTabSize(int)]メソッドでタブサイズの指定が可能
- `JTextPane`
-- `JTextPane`から`StyledDocument`を取得し、`TabStop`から作成した`TabSet`をパラグラフ属性として追加することでタブの幅を指定

-&jnlp;
-&jar;
-&zip;
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/text/TabSet.html TabSet (Java Platform SE 8)]
// - [https://community.oracle.com/thread/1507037 Swing (Archive) - tabsize in JTextPane]
- [[JTextPaneにTabSetを設定してTabStopの文字列揃えをテストする>Swing/TabSet]]
- [[JTextFieldにタブ文字を挿入する>Swing/InsertTabIntoTextField]]

**解説 [#w2ad23ff]
JTextAreaはsetTabSizeメソッドでタブサイズを指定することができますが、JTextPaneでは、上記のサンプルのような方法でタブサイズを指定します。

**参考リンク [#ha0226f7]
-[[Java Forums - tabsize in JTextPane>http://forum.java.sun.com/thread.jspa?forumID=57&threadID=285096]]

**コメント [#h20d6278]
* コメント [#comment]
#comment
#comment