How to clear all textfield of jframe using loop?

[亡魂溺海] 提交于 2020-01-01 14:57:46

问题


I'm developing Java application using NetBeans. I have 5 JTextFields and 2 JTextArea in JFrame. I want to clear them at once using a loop. How can it be done?


回答1:


Iterate over all of the components and set the text of all JTextField and JTextArea objects to an empty String:

//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
    }
}



回答2:


The appropriate code should be this one

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


来源:https://stackoverflow.com/questions/13097626/how-to-clear-all-textfield-of-jframe-using-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!