3

我正在使用 NetBeans 开发 Java 应用程序。我有 5 个JTextFields和 2JTextAreaJFrame。我想使用循环一次清除它们。怎么做到呢?

4

2 回答 2

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
    }
}
于 2012-10-27T06:07:14.117 回答
2

适当的代码应该是这个

    Component[] components = jframe.getContentPane().getComponents();
    for (Component component : components) {
        if (component instanceof JTextField || component instanceof JTextArea) {
            JTextComponent specificObject = (JTextComponent) component;
            specificObject.setText("");
        }
    }
于 2014-12-12T04:11:01.770 回答