setting a JScrollBar in the middle [duplicate]

Basically, you need to know the size of the viewport's viewable area.

Rectangle bounds = scrollPane.getViewport().getViewRect();

Then you need the size of the component, but once it's added to the scroll pane, you can get this from the view port...

Dimension size = scrollPane.getViewport().getViewSize();

Now you need to calculate the centre position...

int x = (size.width - bounds.width) / 2;
int y = (size.height - bounds.height) / 2;

Then you need to simply adjust the view port position...

scrollPane.getViewport().setViewPosition(new Point(x, y));

Now, remember, this is only going to work once the scroll pane has being realised on the screen (or at least it has being laid out within it's parent container)


I'm guessing that the image has not been read at the time you try to execute your code so try something like the following:

label.setIcon( new ImageIcon("...") );

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        Rectangle bounds = scrollPane.getViewport().getViewRect();

        JScrollBar horizontal = scrollPane.getHorizontalScrollBar();
        horizontal.setValue( (horizontal.getMaximum() - bounds.width) / 2 );

        JScrollBar vertical = scrollPane.getVerticalScrollBar();
        vertical.setValue( (vertical.getMaximum() - bounds.height) / 2 );
    }
});

This will add code to the end of the Event Dispatch Thread so hopefully it executes after the image has been read in completely and the scrollbar values have all been updated.


Add an AdjustmentListener and see if that helps. It will let you know if the value of the component changes. That way, when the image is added, the scroll bar's properties will change and you will be notified. You can then try to set the caret position to the mid.

Tutorial: http://examples.javacodegeeks.com/desktop-java/awt/event/adjustmentlistener-example/