views:

46

answers:

1

I have a JPanel with several levels of child components, also with a JScrollPane. I'm placing a focus listener on some of the child components to add some behavior to those components, but I would also like to have that component scroll into the JPanel's viewport when focus is gained.

My question is, does anyone have a general purpose function to do this, similar to the browser DOM function "scrollIntoView"? I've tried muddling through this with various inputs to JComponent.scrollRectToVisible but I guess I haven't figured out the magic word.

Thanks in advance.

+2  A: 

The obvious thing is to call scrollRectToVisible on is the JScrollPane, which will compile fine but won't do what you want. You must call scrollRectToVisible on the object contained in viewport of the scrollpane. The code should look sort of like:

java.awt.Component focusedComponent = evt.getComponent();
panel.scrollRectToVisible(focusedComponent.getBounds(null));
repaint();
eugener
Worked perfectly. That was one of the things that I thought I tried, but I guess I did it incorrectly. Thanks eugener!
bgould