Iterate through all objects in Jframe

久未见 提交于 2019-12-23 15:04:59

问题


I have a simple question. I have a project made with javax.swing.JFrame. I would like to iterate through all the objects that i Have added in the Jframe. Is that possible, how can I do it?


回答1:


this will iterate through all components inside your JFrame's contentPane 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());
}



回答2:


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("");
  }
}



回答3:


An iterative way of traversing all components from a "root" component and "do something" (consumer) with them:

public static void traverseComponentTree( Component root, Consumer<Component> consumer ) {
    Stack<Component> stack = new Stack<>();
    stack.push( root );
    while ( !stack.isEmpty() ) {
        Component current = stack.pop();
        consumer.accept( current ); // Do something with the current component
        if ( current instanceof Container ) {
            for ( Component child : ( (Container) current ).getComponents() ) {
                stack.add( child );
            }
        }
    }
}


来源:https://stackoverflow.com/questions/10271116/iterate-through-all-objects-in-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!