• 追加された行はこの色です。
  • 削除された行はこの色です。
#navi(../)
*JTextPaneに修飾した文字列を挿入 [#md42acc5]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-01-13~
更新日:&lastmod;
---
category: swing
folder: StyleConstants
title: JTextPaneに修飾した文字列を挿入
tags: [JTextPane, StyledDocument]
author: aterai
pubdate: 2004-01-12
description: JTextPaneにスタイル付けした文字列を挿入してログ風に表示します。
image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTT31r9lEI/AAAAAAAAAlI/7PqL2Aa3UJU/s800/StyleConstants.png
---
* 概要 [#summary]
`JTextPane`にスタイル付けした文字列を挿入してログ風に表示します。

#contents
**概要 [#p28a05e7]
JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTT31r9lEI/AAAAAAAAAlI/7PqL2Aa3UJU/s800/StyleConstants.png)

http://terai.xrea.jp/swing/styleconstants/screenshot.png
* サンプルコード [#sourcecode]
#code(link){{
StyledDocument doc = jtp.getStyledDocument();
Style def = doc.getStyle(StyleContext.DEFAULT_STYLE);
Style error = doc.addStyle("error", def);
StyleConstants.setForeground(error, Color.RED);
// ...

**サンプルコード [#s34357fb]
 private void append(final String str, final boolean flg) {
   SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       SimpleAttributeSet sas = null;
       if(!flg) {
         //sas = new SimpleAttributeSet(jtp.getCharacterAttributes());
         sas = new SimpleAttributeSet();
         StyleConstants.setForeground(sas, Color.red);
         //StyleConstants.setBold(sas, true);
         //StyleConstants.setFontFamily(sas, "Monospaced");
         //StyleConstants.setFontSize(sas, 32);
       }
       try{
         Document doc = jtp.getDocument();
         doc.insertString(doc.getLength(), str+"\n", sas);
         jtp.setCaretPosition(doc.getLength());
       }catch(BadLocationException e) {}
     }
   });
 }
private void append(String str, boolean flg) {
  String style = flg ? StyleContext.DEFAULT_STYLE : "error";
  StyledDocument doc = jtp.getStyledDocument();
  try {
    doc.insertString(doc.getLength(), str + "\n", doc.getStyle(style));
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
}
}}

-[[サンプルを起動>http://terai.xrea.jp/swing/styleconstants/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/styleconstants/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/styleconstants/src.zip]]
**解説 [#r6829207]
StyleConstantsで文字属性をSimpleAttributeSetに設定し、これを文字列と一緒にDocument#insertStringメソッドを使って挿入しています。
* 解説 [#explanation]
上記のサンプルでは、以下の手順で`JTextPane`にスタイルを設定した文字列を追加しています。

//**参考リンク
**コメント [#zd8e1d8b]
- `JTextPane`から`StyledDocument`を取得
- 予め設定しておいたエラー表示用の文字属性スタイルを`StyledDocument#getStyle("error")`メソッドで取得
- このスタイルと文字列と合わせて`Document#insertString(...)`メソッドで挿入

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/tutorial/uiswing/components/text.html Using Text Components (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)]

* コメント [#comment]
#comment
- 一々、`SimpleAttributeSet`を生成していたのを修正。 -- &user(aterai); &new{2010-12-06 (月) 22:24:36};

#comment