如何在单击 JButton 时清除 JFrame 中的所有组件值



我需要清除JFrame中所有组件的值。我尝试了以下逻辑,但值仍然出现在框中。

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);
    }
}

你需要递归地执行此操作

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);
        }
    }
}

您需要调用它:

clearAll(frame.getContentPane());

最新更新