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

[3077 byte] By [Lanugoa] at [2007-10-2 10:47:34]
# 1
Here is an example that removes lines when the maximum number of lines is exceeded. The same concept can be used for characters: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=689486
camickra at 2007-7-13 3:03:07 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thank you for your prompt and kind reply.Everything seems to be working correctly - the trick being calling setCaretPosition at the right time, I suppose.Pierluigi Rolando
Lanugoa at 2007-7-13 3:03:07 > top of Java-index,Desktop,Core GUI APIs...