• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextPaneに修飾した文字列を挿入
#navi(../)
#tags()
RIGHT:Posted by &author(aterai); at 2004-01-12
*JTextPaneに修飾した文字列を挿入 [#md42acc5]
JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。
---
title: JTextPaneに修飾した文字列を挿入
tags: [JTextPane, StyledDocument]
author: aterai
pubdate: 2004-01-12
description: JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。
---
* 概要 [#md42acc5]
`JTextPane`に、スタイル付けした文字列を挿入して、ログ風に表示します。

-&jnlp;
-&jar;
-&zip;
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTT31r9lEI/AAAAAAAAAlI/7PqL2Aa3UJU/s800/StyleConstants.png)

//#screenshot
#ref(http://lh5.ggpht.com/_9Z4BYR88imo/TQTT31r9lEI/AAAAAAAAAlI/7PqL2Aa3UJU/s800/StyleConstants.png)

**サンプルコード [#s34357fb]
* サンプルコード [#s34357fb]
#code(link){{
StyledDocument doc = jtp.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(
    StyleContext.DEFAULT_STYLE);

Style regular = doc.addStyle("regular", def);
//StyleConstants.setForeground(def, Color.BLACK);

Style error = doc.addStyle("error", regular);
StyleConstants.setForeground(error, Color.RED);
}}
#code{{
private void append(String str, boolean flg) {
  String style = flg?"regular":"error";
  StyledDocument doc = jtp.getStyledDocument();
  try{
    doc.insertString(doc.getLength(), str+"\n", doc.getStyle(style));
  }catch(BadLocationException e) {
    e.printStackTrace();
  }
}
}}

**解説 [#r6829207]
%%StyleConstantsで文字属性をSimpleAttributeSetに設定し、%% 予め設定しておいたエラー表示用のスタイル(文字属性)を、StyledDocument#getStyle("error")で取得し、これを文字列と一緒にDocument#insertStringメソッドを使って挿入しています。
* 解説 [#r6829207]
予め設定しておいたエラー表示用のスタイル(文字属性)を、`StyledDocument#getStyle("error")`で取得し、これを文字列と一緒に`Document#insertString`メソッドを使って挿入しています。

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

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

#comment