Originariamente inviato da tulipan
come faccio ad "appendere" del testo ad un jTextPane?
Ecco un esempio completo, con tanto di attributi differenti.
codice:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TestFrame extends JFrame
{
public TestFrame ()
{
super ("Test Frame");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize (300, 300);
StyledDocument document = new DefaultStyledDocument ();
SimpleAttributeSet attributes;
try
{
attributes = new SimpleAttributeSet ();
StyleConstants.setForeground (attributes, Color.RED);
StyleConstants.setBold (attributes, true);
document.insertString (document.getLength (), "rosso/grassetto ", attributes);
attributes = new SimpleAttributeSet ();
StyleConstants.setBackground (attributes, Color.YELLOW);
StyleConstants.setItalic (attributes, true);
document.insertString (document.getLength (), "sfondo giallo/corsivo ", attributes);
}
catch (BadLocationException e) { }
JTextPane textPane = new JTextPane (document);
JScrollPane scrollPane = new JScrollPane (textPane);
getContentPane ().add (scrollPane);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
TestFrame f = new TestFrame ();
f.setVisible (true);
}
});
}
}
La parte relativa agli attributi credo che sia più che chiara e comprensibile: ho creato un SimpleAttributeSet, ho impostato diversi attributi (ci sono svariati metodi setXXX in StyleConstants) e quindi ho aggiunto la stringa specificando offset e gli attributi.
Passando il valore di getLength() come offset si aggiunge il testo al fondo. La eccezione BadLocationException viene lanciata da insertString se la posizione non è corretta. Ma facendo le cose come si deve (es. passando getLength() che è un valore corretto) non dovrebbe presumibilmente capitare.