Help with scrollRectToVisible

Hey,

I am having a problem using the scrollRectToVisible method on a JScrollPane. I have an application where the layout is like so:

JSplitPane (splitPane)

->JPanel on the right side (rightPanel) (and ignoring the leftfor now)

-->rightPanel contains a JScrollPane (rightScrollPane)

>rightScrollPane contains a dynamically sizable JPanel (contentPanel). Dynamically changes size via a JSlider (scaleSlider)

When the user interacts with the scaleSlider it changes the width of the contentPanel and will introduce a scrollBar in the rightScrollPane if the contentPanel grow larger than the viewport area. In the viewport of the rightScrollPane I would like to always display an area of the contentPanel that dynamically changes in respect to the size of the contentPanel.I am having problems with this: here is my code:

privatevoid scaleSliderStateChanged(ChangeEvent e){

JSlider source = (JSlider)e.getSource();

int scale = source.getValue();

contentPanel.setSize(new Dimension(scale, contentPanel.getHeight()));

contentPanel.setPreferredSize(new Dimension(scale, contentPanel.getHeight()));

//for brevity lets say the area of the contentPanel i want to display is

//always in the center (width/2).

Rectangle tempRect = contentPanel.getBounds();

tempRect.setBounds(tempRect.width/2, 20, 200, 200);

rightScrollPane.getViewport().scrollRectToVisible(tempRect);

So i think that the this should produce a rectangle which is has an inital x location that is half the width, an inital y = 20, whose width and height is 200. All that really matters to me here is that the inital x location is in the viewport all the time. I would think that this should allow the user to manipulate the scaleSlider and in effect change the width of the contentPanel furthermore always retaining the same horizontally centered location of the contentPanel in the rightScrollPane.

However upon execution and manipulation of the scaleSlider the width of the contentPanels width is changed as desired, however the horizontal scroll bar immediately moves to the far right and stays there. Can anyone tell me what i am doing wrong here?

thanks in advance for your help.

[2560 byte] By [b12sa] at [2007-11-27 3:06:25]
# 1

scrollRectToVisible() is really meant to be used on the component added to the scrollPane. So in your case the panel you just resized.

If that doesn't work then add the code to a SwingUtilities.invokeLater(...) to make sure it gets executed after all currently queued events get processed.

Finally if that doesn't work, the try using the setViewPostion() method of the JViewport.

camickra at 2007-7-12 3:52:45 > top of Java-index,Desktop,Core GUI APIs...
# 2
well ok... Your first comment which corrected my knowledge of the scrollRectToVisible() has me back on track. thank you
b12sa at 2007-7-12 3:52:45 > top of Java-index,Desktop,Core GUI APIs...