Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center the vertical and horizontal scrollbars in a JScrollPane?

I have a JPanel with a JLabel in it, added to a JScrollPane. I have an actionListener that calls JLabel.setIcon("file.jpg");. The image is displayed in the JScrollPane correctly and is full size. The scrollbars appear perfectly. I am trying to position the vertical and horizontal scrollbars in the center by default so you are looking at the center of the image by default.

Is there a JScrollPane method that will position the viewport on the center of the image? Or could I manually set the position of each scrollbar to max size divided by 2?

I have tried

JScrollPane.getVerticalScrollBar().setValue(JScrollPane.getVerticalScrollBar().getMaximum() / 2);

While it compiles it does not center the scrollbar. I have also tried setting the layout manager of my JPanel to GridBagLayout but that doesn't work either.

like image 646
David Nelson Avatar asked Dec 19 '22 20:12

David Nelson


1 Answers

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)

like image 75
MadProgrammer Avatar answered Feb 15 '23 22:02

MadProgrammer