Swing/StyleConstants のバックアップの現在との差分(No.22)
- 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();
Style def = doc.getStyle(StyleContext.DEFAULT_STYLE);
Style error = doc.addStyle("error", def);
StyleConstants.setForeground(error, Color.RED);
#spandel
View in GitHub: Java, Kotlin#spanend
private void append(String str, boolean flg) {
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
にスタイルを設定した文字列を追加しています。
-
JTextPane
からStyledDocument
を取得 - 予め設定しておいたエラー表示用の文字属性スタイルを
StyledDocument#getStyle("error")
メソッドで取得 - このスタイルと文字列と合わせて
Document#insertString(...)
メソッドで挿入
参考リンク
- Using Text Components (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)