DIneSH dinu
DIneSH dinu

Reputation: 21

How to clear all the component values in a JFrame on clicking JButton

I need to clear the values of all the components in a JFrame. I have tried the following logic but the values are still appearing in the boxes.

for(Component c:frame.getComponents()){
    if(c instanceof JTextField || c instanceof JTextArea){
        ((JTextComponent) c).updateUI();
    }else if(c instanceof JRadioButton){
        ((JRadioButton) c).setSelected(false);
    }else if(c instanceof JDateChooser){
        ((JDateChooser) c).setDate(null);
    }
}

Upvotes: 1

Views: 456

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

You need to do it recursevly

private void clearAll(Container aContainer) {
    for(Component c:aContainer.getComponents()) {
        if(c instanceof JTextField || c instanceof JTextArea){
            ((JTextComponent) c).setText("");
        }else if(c instanceof JRadioButton){
            ((JRadioButton) c).setSelected(false);
        }else if(c instanceof JDateChooser){
             ((JDateChooser) c).setDate(null);
        }else if (c instanceof Container) {
             clearAll((Container) c);
        }
    }
}

You need to call it:

clearAll(frame.getContentPane());

Upvotes: 1

Related Questions