我有一个简单的问题。我有一个用 javax.swing.JFrame 制作的项目。我想遍历我在 Jframe 中添加的所有对象。这可能吗,我该怎么做?
问问题
6047 次
3 回答
11
这将遍历 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());
}
于 2012-04-22T19:18:28.880 回答
0
以下代码将使用 FOR 循环清除 JFrame 中的所有 JTextField
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("");
}
}
于 2014-08-20T12:43:52.807 回答
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 );
}
}
}
}
于 2019-12-20T21:27:22.407 回答