遍历Jframe中的所有对象

问题描述:

我有一个简单的问题。我有一个用javax.swing.JFrame制作的项目。我想遍历Jframe中添加的所有对象。这是可能的,我该怎么做?遍历Jframe中的所有对象

这会遍历你的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()); 
} 
+0

感谢清除一个JFrame所有JTextField的答案,它的作品。奇怪的是,我不能对这些组件做任何事情。在for循环中,我有这样的条件:if(c instanceof JTextField){JTextField j =(JTextField)c; System.out.println(j); j.setText(“ABCD”); }它打印j的tostring,但没有设置文本,任何想法? – 2012-04-22 21:46:28

+0

*“有什么想法?”* 1)询问另一个(新)问题。 2)添加一个[SSCCE](http://sscce.org/)。 3)解释这种不寻常的需求的用例,需求。 4)确保在EDT上进行更新。 – 2012-04-23 07:20:16

下面的代码将使用FOR循环

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