我有一个简单的问题。我有一个用javax.swing.JFrame制作的项目。我想迭代我在Jframe中添加的所有对象。这可能,我该怎么做?
答案 0 :(得分:8)
这将迭代JFrame的contentPane中的所有组件并将它们打印到控制台:
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());
}
答案 1 :(得分:0)
以下代码将使用FOR循环
清除JFrame中的所有JTextFieldComponent 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("");
}
}
答案 2 :(得分:0)
一种遍历“根”组件中的所有组件并对其执行“消费”的迭代方法:
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 );
}
}
}
}