Reputation: 21
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
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