我需要清除 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());
关于java - 如何在单击 JButton 时清除 JFrame 中的所有组件值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554467/