问题
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