Search code examples
javaswingjframejtextfieldjtextarea

How to clear all textfield of jframe using loop?


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?


Solution

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