如何使用循环清除jframe的所有textfield?

时间:2012-10-27 05:49:05

标签: java swing jframe jtextfield jtextarea

我正在使用NetBeans开发Java应用程序。我在JTextFields中有5 JTextArea和2 JFrame。我想使用循环立即清除它们。怎么办呢?

2 个答案:

答案 0 :(得分:6)

迭代所有组件并将所有JTextFieldJTextArea对象的文本设置为空字符串:

//Note: "this" should be the Container that directly contains your components
//(most likely a JPanel).
//This won't work if you call getComponents on the top-level frame.
for (Component C : this.getComponents())
{    
    if (C instanceof JTextField || C instanceof JTextArea){

        ((JTextComponent) C).setText(""); //abstract superclass
    }
}

答案 1 :(得分:2)

适当的代码应该是这个

    Component[] components = jframe.getContentPane().getComponents();
    for (Component component : components) {
        if (component instanceof JTextField || component instanceof JTextArea) {
            JTextComponent specificObject = (JTextComponent) component;
            specificObject.setText("");
        }
    }