Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a component is within a specific container

Tags:

java

swing

I have an application with a lot of swing components, nested in several containers. I'm implementing a right-click popup menu, showing information based upon the context the component is in.

To give an example: If I right-click on a JTextField, I want to display "foo" in the popup if the textfield is within a JScrollPane, and "bar" if it is not. But the JTextField itself may be nested in several other JPanels.

i could do something like this:

public static boolean isInScrollPane(JComponent comp) {

    Container c = comp.getParent();

    while (c != null) {         
        if (c instanceof JScrollPane) {
            return true;
        } else {
            c = c.getParent();
        }
    }
    return false;
}

But i bet there is a much better solution already available and I just didn't find it.

Could someone please give me a hint?

like image 293
moeTi Avatar asked Apr 30 '12 10:04

moeTi


1 Answers

Your code basically matches the SwingUtilies.getAncestorOfClass() method. Your code can therefore be simplified to:

public static boolean isInScrollPane(JComponent comp)
{
  return SwingUtilities.getAncestorOfClass(JScrollPane.class, comp) != null;
}
like image 152
Greg Kopff Avatar answered Sep 27 '22 23:09

Greg Kopff