This is a problem that has vexed me for a number of years. The user is scrolling through a text document contained in an JEditorPane which is in turn contained in a JScrollPane. The user performs some function using a button which changes the text (it highlights certain sections of the text). I then refresh the document in the JeditorPane to reflect the highlighting (using html tags). But when I do this, the document scrolls back to the top. I want the document to stay in the same position that the user was in right before taking the action. Note, the user has not selected any text in th开发者_JS百科e document so I can't scroll to a selection point (that technique does work if text is selected, but alas I can't do it in this case). How do I preserve the position in the JScrollPane and scroll to the position that the user was at prior to taking the action?
Thank you
You can use JViewport.scrollRectToVisible() to jump to a certain section of a document in a JScrollPane. You can snapshot the current position before performing the action with JViewPort.getViewRect()
http://download.oracle.com/javase/6/docs/api/javax/swing/JViewport.html
Note, the user has not selected any text in the document so I can't scroll to a selection point
Get the selection indices before updating, then call setCaretPosition(previousStart)
then moveCaretPosition(previousEnd)
afterwards.
You can also use:
Point p = scrollPane.getViewport().getViewPosition();
// do stuff
scrollPane.getViewport().setViewPosition();
I tried all of these potential solutions. Unfortunately, for whatever reason, they didn't work. This is the code that actually solved the problem for me.
/* This code is executed, before the JeditorPane is updated: */
int spoint = detailpane.scrollPane.getVerticalScrollBar().getValue();
/* Then to restore the scroll to where it was before the update, the following code is executed*/
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
detailpane.scrollPane.getVerticalScrollBar().setValue(spoint);
}
});
/* Note because of the usual weirdnesses associated with Swing which is not thread safe, you need to enclosed the setValue within in a Runnable. */
精彩评论