Swing/StyleConstants のバックアップの現在との差分(No.13)
TITLE:JTextPaneに修飾した文字列を挿入
JTextPaneに修飾した文字列を挿入
編集者:Terai Atsuhiro~
作成日:2004-01-13
更新日:2021-12-24 (金) 12:38:13
概要
JTextPane
にスタイル付けした文字列を挿入してログ風に表示します。
Screenshot
Advertisement
概要
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
#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
#spanadd
View in GitHub: Java, Kotlinサンプルコード
private void append(final String str, final boolean error) { SwingUtilities.invokeLater(new Runnable() { public void run() { 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) {} } }); }
解説
上記のサンプルでは、以下の手順でJTextPane
にスタイルを設定した文字列を追加しています。
- &jnlp;
- &jar;
- &zip;
-
JTextPane
からStyledDocument
を取得 - 予め設定しておいたエラー表示用の文字属性スタイルを
StyledDocument#getStyle("error")
メソッドで取得 - このスタイルと文字列と合わせて
Document#insertString(...)
メソッドで挿入
解説
StyleConstantsで文字属性をSimpleAttributeSetに設定し、これを文字列と一緒にDocument#insertStringメソッドを使って挿入しています。参考リンク
- Using Text Components (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)