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

-&jnlp;
-&jar;
-&zip;

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

**サンプルコード [#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(final String str, final boolean error) {
  SimpleAttributeSet sas = null;
  if(!error) {
    //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);
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();
  }
  try{
    Document doc = jtp.getDocument();
    doc.insertString(doc.getLength(), str+"\n", sas);
    jtp.setCaretPosition(doc.getLength());
  }catch(BadLocationException e) {}
}
}}

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

//**参考リンク
**参考リンク [#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};

#comment