3

I think we can use jScrollPane.getComponents() to get awt components of a jscrollpane. My question is: is there a way to get swing components of a container some how?

Bee
  • 12,251
  • 11
  • 46
  • 73
  • 4
    Swing components extend AWT components. (So `getComponents()` reports both). – Andrew Thompson Jun 26 '11 at 18:35
  • Often you're better off holding references to the important components rather than having to recurse through nested containers in order to find your needle in a haystack. – Hovercraft Full Of Eels Jun 26 '11 at 19:53
  • 2
    Note that so far the two answers given do not use recursion and will get you nothing but the JScrollPane's JViewport. – Hovercraft Full Of Eels Jun 26 '11 at 19:57
  • 1
    @Hovercraft (Monday morning, nitpicking time :-) its viewport_s_ (there can be several) and its scrollbars. Disagree with your other comment: if you need to often talk to a particular component its usually time to carefully re-think the design – kleopatra Jun 27 '11 at 05:54

2 Answers2

2

All Swing components extend JComponent.

Component[] comps = jScrollPane.getComponents();
ArrayList<JComponent> swingComps = new ArrayList<JComponent>();

for(Component comp : comps) {
     if(comp instanceof JComponent) {
          swingComps.add((JComponent) comp);
     }
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
1

You can call getComponents then test to see if it is an instance of JComponent. A method would be like:

ArrayList jcomponents = new ArrayList();
for (Component c : container.getComponents())
{
      if (c instanceof JComponent)
      {
            jcomponents.add(c);
      }
 }
Nathan Moos
  • 3,563
  • 2
  • 22
  • 27