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

Usage: #tags(tags)
Posted by at 2004-01-12

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

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

  • &jnlp;
  • &jar;
  • &zip;
StyleConstants.png

サンプルコード

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);
View in GitHub: Java, Kotlin
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();
  }
}

解説

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

参考リンク

コメント

  • 一々、SimpleAttributeSetを生成していたのを修正。 -- aterai