循环通过JPanel [英] loop through JPanel

查看:148
本文介绍了循环通过JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击清除按钮时,为了在 JPanel 上初始化所有 JTextfField ,我需要循环遍历 JPanel (而不是将所有单个字段设置为)。

In order to initialize all JTextfFields on a JPanel when users click a "clear button", I need to loop through the JPanel (instead of setting all individual field to "").

我如何使用for-each循环,以便遍历 JPanel 搜索 JTextField s?

How can I use a for-each loop in order to iterate through the JPanel in search of JTextFields?

推荐答案

for (Component c : pane.getComponents()) {
    if (c instanceof JTextField) { 
       ((JTextField)c).setText("");
    }
}

但如果你有更深层嵌套的JTextFields,你可以使用以下递归形式:

But if you have JTextFields more deeply nested, you could use the following recursive form:

void clearTextFields(Container container) {
    for (Component c : container.getComponents()) {
        if (c instanceof JTextField) {
           ((JTextField)c).setText("");
        } else
        if (c instanceof Container) {
           clearTextFields((Container)c);
        }
    }
}

编辑: Tom Hawtin的一个示例 - 提示建议将在您的框架类中包含列表:

A sample for Tom Hawtin - tackline suggestion would be to have list in your frame class:

List<JTextField> fieldsToClear = new LinkedList<JTextField>();

当您初始化单个文本字段时,请将它们添加到此列表中:

and when you initialize the individual text fields, add them to this list:

someField = new JTextField("Edit me");
{ fieldsToClear.add(someField); }

当用户点击清除按钮时,只需:

and when the user clicks on the clear button, just:

for (JTextField tf : fieldsToClear) {
    tf.setText("");
}

这篇关于循环通过JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆