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?
Your code basically matches the
SwingUtilies.getAncestorOfClass()method. Your code can therefore be simplified to: