JTextPane and limited length documents
Hi,
I would like to implement a JTextPane that contains only a preordinate amount of text (measured in characters).
My application consists of a JScrollPane containing a JTextPane, and a JTextField (that is not included in the JScrollPane) from which the text is taken on an action event.
Here follows the action handler I am using:
textField.addActionListener(new ActionListener(){
publicvoid actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable(){
publicvoid run(){
try{
doc.insertString(doc.getLength(), textField.getText() +'\n',null);
}catch(BadLocationException b){
// do nothing
}
textField.selectAll();
// Keep the text area down to a certain character size
int idealSize = 40;
int maxExcess = 0;
int excess = textPane.getDocument().getLength() - idealSize;
if (excess >= maxExcess){
try{
doc.remove(0, excess);
}catch(BadLocationException b){
// do nothing
}
}
// Make sure the last line is always visible
textPane.setCaretPosition(textPane.getDocument().getLength());
//Dimension n = textPane.getSize();
//textPane.scrollRectToVisible(new Rectangle(0, n.height-1, 1, 1));
}
});
}
});
The problem is, it doesn't work. I test it by typing a single digit on every row, and as soon as I reach the dimension limit older text is correctly removed from the document, new characters are appended, but the scrollbar doesn't scroll to the newly added line.
I have also tried the scrollRectToVisible() way, which you can test by uncommenting those two lines, but it appears to work even less (though I'm pretty sure it is my own fault with that).
Is there a canonical way to do what I need?
Thank you in advance,
Pierluigi Rolando

