Swing/StyleConstants のバックアップの現在との差分(No.15)
TITLE:JTextPaneに修飾した文字列を挿入
Posted by terai at 2004-01-13
JTextPaneに修飾した文字列を挿入
JTextPaneに、スタイル付けした文字列を挿入して、ログ風に表示します。- category: swing folder: StyleConstants title: JTextPaneに修飾した文字列を挿入 tags: [JTextPane, StyledDocument] author: aterai pubdate: 2004-01-12 description: JTextPaneにスタイル付けした文字列を挿入してログ風に表示します。 image:
概要
JTextPane
にスタイル付けした文字列を挿入してログ風に表示します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
#screenshot
サンプルコード
#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
**サンプルコード [#s34357fb]
#spanend
#spandel
#code{{
#spanend
#spandel
private void append(final String str, final boolean error) {
#spanend
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);
#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();
}
try{
Document doc = jtp.getDocument();
doc.insertString(doc.getLength(), str+"\n", sas);
jtp.setCaretPosition(doc.getLength());
}catch(BadLocationException e) {}
}
View in GitHub: Java, Kotlin解説
StyleConstantsで文字属性をSimpleAttributeSetに設定し、これを文字列と一緒に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)