7

Imagine you have a JScrollPane and many JLabels or any other JComponents added to it.

How would you check if a certain component is visible/partially visible/not visible to user? (scrolling)

I have tried to Google but could not find an easy solution. Is there some existing method I am missing or we have to deal with coordinates and rectangular comparison?

UPD: the following is not working in my case. It seem to relate to JLabel.setVisible(true/false) but not being inside JScrollPane

JLabel.isVisible();
Nikolay Kuznetsov
  • 8,896
  • 9
  • 49
  • 94

1 Answers1

14

Have a look at JComponent java doc:

Rectangle r = child.getVisibleRect();
if (r.getSize().equals(child.getSize())) {
   // fully visible
} else if (r.isEmpty()) {
   // not visible
} else {
  // partly visible
}

Edit

changed the condition for not-visible to use Rectangle api - thanks to @mKorbel for reminding me :-)

dldnh
  • 8,745
  • 3
  • 33
  • 50
kleopatra
  • 49,346
  • 26
  • 88
  • 189
  • 1
    @kleopatra why not to use if (r.intersects(child)) { – mKorbel Nov 29 '12 at 16:23
  • @mKorbel an option if you were interested only in whether any part of the child or nothing is visible. And would require a second rectange. Or maybe I misunderstand what you are suggesting? – kleopatra Nov 30 '12 at 10:36
  • I've done that but if you move the scroll bar and some new buttons appear they still print that they are not visible. The r rectangle never changes in respect to the scrollbar nor the components scrollbar. Any solution? Or i am doing something wrong? – Kostas Thanasis Mar 23 '20 at 19:42
  • i have found a solution. I replaced your first line of code with this: Rectangle r = scrollPane.getViewport().getViewRect(). Where scrollPane obviously is the variable pointing to the Scroll Pane. – Kostas Thanasis Mar 23 '20 at 19:54