TITLE:JTextPaneに修飾した文字列を挿入

JTextPaneに修飾した文字列を挿入

編集者:Terai Atsuhiro~

作成日:2004-01-13
更新日:2021-12-24 (金) 12:38:13
  • 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

概要

JTextPaneにスタイル付けした文字列を挿入してログ風に表示します。

概要

JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。

サンプルコード

#spanend
#spanadd
StyledDocument doc = jtp.getStyledDocument();
#spanend
#spanadd
Style def = doc.getStyle(StyleContext.DEFAULT_STYLE);
#spanend
#spanadd
Style error = doc.addStyle("error", def);
#spanend
#spanadd
StyleConstants.setForeground(error, Color.RED);
#spanend
#spanadd
// ...
#spanend

#spandel
#screenshot
#spanend
#spandel

#spanend
#spandel
**サンプルコード [#s34357fb]
#spanend
#spandel
#code{{
#spanend
 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);
   }
   try{
     Document doc = jtp.getDocument();
     doc.insertString(doc.getLength(), str+"\n", sas);
     jtp.setCaretPosition(doc.getLength());
   }catch(BadLocationException e) {}
 }
#spanadd
private void append(String str, boolean flg) {
#spanend
  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();
  }
#spanadd
}
#spanend
View in GitHub: Java, Kotlin
  • &jnlp;
  • &jar;
  • &zip;

解説

StyleConstantsで文字属性をSimpleAttributeSetに設定し、これを文字列と一緒にDocument#insertStringメソッドを使って挿入しています。

解説

上記のサンプルでは、以下の手順でJTextPaneにスタイルを設定した文字列を追加しています。

コメント

  • JTextPaneからStyledDocumentを取得
  • 予め設定しておいたエラー表示用の文字属性スタイルをStyledDocument#getStyle("error")メソッドで取得
  • このスタイルと文字列と合わせてDocument#insertString(...)メソッドで挿入

参考リンク

コメント