moeTi
moeTi

Reputation: 3904

Find out if a component is within a specific container

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?

Upvotes: 6

Views: 2297

Answers (1)

Greg Kopff
Greg Kopff

Reputation: 16625

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;
}

Upvotes: 9

Related Questions