Iterate through all objects in Jframe

I have a simple question. I have a project with javax.swing.JFrame. I would like to repeat all the objects that I added in Jframe. Is this possible, how can I do this?

+3
source share
2 answers

this will cause all components to transition inside your JFrame content panel and print them to the console:

public void listAllComponentsIn(Container parent)
{
    for (Component c : parent.getComponents())
    {
        System.out.println(c.toString());

        if (c instanceof Container)
            listAllComponentsIn((Container)c);
    }
}

public static void main(String[] args)
{
    JFrame jframe = new JFrame();

    /* ... */

    listAllComponentsIn(jframe.getContentPane());
}
+8
source

The following code will clear all JTextFields in a JFrame using a FOR loop

Component component = null; // Stores a Component

Container myContainer;
myContainer = this.getContentPane();
Component myCA[] = myContainer.getComponents();

for (int i=0; i<myCA.length; i++) {
  JOptionPane.showMessageDialog(this, myCA[i].getClass()); // can be removed
  if(myCA[i] instanceof JTextField) {
    JTextField tempTf = (JTextField) myCA[i];
    tempTf.setText("");
  }
}
0
source

All Articles