Search code examples
javaswingscrolljscrollpanejscrollbar

Put the bar of a JScrollPane scroll bar at XXX without "flashing"


I'm building a JScrollPane to set scrollable a JPanel which contains a JTextPane and a JTable.

When I load the frame I initialize the JTextPane with a very long text, then the scroll bar moves down til the end of my document.

I'd like to get this scroll bar on top of the document instead. So I put the value of my scroll bar to 0, after the text loading:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        myScrollPane.getVerticalScrollBar().setValue(0);
    }
});

It works fine (i.e. I get the scroll bar on top) but the rendered behavior is pretty ugly. Now it loads the text, shows the end (with the scroll bar at the bottom of the text pane), then immediately (few milliseconds, but still visible) moves up to get the scroll bar on top. The resulting effect is a "flash" for the user, which is very unpleasant. And I have the same problem each time I reload the whole document.

How could I avoid that?

Thanks.


Solution

  • Finally I put the default caret to NEVER_UPDATE.

    JTextPane textPane = new JTextPane();
    DefaultCaret caret = (DefaultCaret) textPane.getCaret();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    

    Here is the documentation of setUpdatePolicy(). Then I update the caret by myself.