Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get shown component in JScrollPane

I have a JScrollPane containing a JPanel. I fill this JPanel with many buttons.

Is there any possibility to get the currently shown buttons?

I know I can access the children of a JPanel via jpanel.getComponents() but those are all components in this pane; I want only the ones that are currently on screen.

like image 312
Leon Avatar asked Dec 13 '11 07:12

Leon


3 Answers

As already commented to @mKorbel's answer:

  • it's correct that you need the child bounds
  • it's correct that you need to intersect those bounds with "something"
  • it's wrong that you need the containing viewport (nor the scrollpane)

JComponents have an API to get their currently visible part independently of how/where exactly they are currently shown, so the "something" is the JComponent's visibleRect:

Rectangle visibleRect = myPanel.getVisibleRect();
for (Component child : myPanel.getComponents()) {
   Rectangle childBounds = child.getBounds();
   if (childBounds.intersects(visibleRect)) {
       // do stuff
   }
}
like image 79
kleopatra Avatar answered Oct 07 '22 21:10

kleopatra


I assume that this container is already visible on the screen, then I suggest

1) to extract JViewPort from JScrollPane,

2) addChangeListener to JViewPort

3) each visible JComponent(s) returns Rectangle

4) and Rectangle#intersects returns Boolean value if is JComponent(s) visible or not in JViewPort

like image 32
mKorbel Avatar answered Oct 07 '22 21:10

mKorbel


How about asking the components if they're visible:

for ( Component component : jpanel.getComponents() ) {
    if ( component instanceof JButton && component.isShowing() ) {
        // We've found a button that is showing...
    }
}
  • Component#isShowing()
like image 37
Nate W. Avatar answered Oct 07 '22 22:10

Nate W.