• category: swing folder: StyleConstants title: JTextPaneに修飾した文字列を挿入 tags: [JTextPane, StyledDocument] author: aterai pubdate: 2004-01-12 description: JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。 description: JTextPaneにスタイル付けした文字列を挿入してログ風に表示します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTT31r9lEI/AAAAAAAAAlI/7PqL2Aa3UJU/s800/StyleConstants.png

概要

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

概要

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

サンプルコード

サンプルコード

StyledDocument doc = jtp.getStyledDocument();
#spandel
Style def = StyleContext.getDefaultStyleContext().getStyle(
#spanend
    StyleContext.DEFAULT_STYLE);
#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
Style regular = doc.addStyle("regular", def);
#spanend
#spandel
//StyleConstants.setForeground(def, Color.BLACK);
#spanend
#spandel

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

解説

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

解説

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

参考リンク

コメント

参考リンク

コメント