Swing/StyleConstants のバックアップの現在との差分(No.19)
- category: swing folder: StyleConstants title: JTextPaneに修飾した文字列を挿入 tags: [JTextPane, StyledDocument] author: aterai pubdate: 2004-01-12 description: JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。 description: JTextPaneにスタイル付けした文字列を挿入してログ風に表示します。 image:
概要
JTextPane
に、スタイル付けした文字列を挿入して、ログ風に表示します。
概要
JTextPane
にスタイル付けした文字列を挿入してログ風に表示します。
Screenshot
Advertisement
サンプルコード
サンプルコード
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) {
e.printStackTrace();
}
}
解説
予め設定しておいたエラー表示用のスタイル(文字属性)を、StyledDocument#getStyle("error")
で取得し、これを文字列と一緒にDocument#insertString
メソッドを使って挿入しています。
解説
上記のサンプルでは、以下の手順でJTextPane
にスタイルを設定した文字列を追加しています。
参考リンク
- Using Text Components (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
-
JTextPane
からStyledDocument
を取得 - 予め設定しておいたエラー表示用の文字属性スタイルを
StyledDocument#getStyle("error")
メソッドで取得 - このスタイルと文字列と合わせて
Document#insertString(...)
メソッドで挿入