JPanel问题中的Java清除组件

时间:2014-07-21 13:36:26

标签: java swing jpanel

我正在尝试清除JPanel中的所有内容,而不是硬编码。我有一个for循环,它对JTextFields很有用,但没有别的。注释掉的块使一切正常,但我想看看是否可以动态添加包含在内的JPanel。

List<Component> controls = new ArrayList<>();
controls.addAll(Arrays.asList(this.getComponents()));
/*controls.addAll(Arrays.asList(jPanel1.getComponents()));
controls.addAll(Arrays.asList(jPanel2.getComponents()));
controls.addAll(Arrays.asList(jPanel3.getComponents()));
controls.addAll(Arrays.asList(jPanel4.getComponents()));
controls.addAll(Arrays.asList(jPanel5.getComponents()));
controls.addAll(Arrays.asList(jPanel6.getComponents()));
controls.addAll(Arrays.asList(jPanel7.getComponents()));
controls.addAll(Arrays.asList(jPanel8.getComponents()));
controls.addAll(Arrays.asList(jPanel9.getComponents()));
controls.addAll(Arrays.asList(jPanel10.getComponents()));
controls.addAll(Arrays.asList(jPanel11.getComponents()));
controls.addAll(Arrays.asList(jPanel12.getComponents()));
controls.addAll(Arrays.asList(jPanel13.getComponents()));*/
for(Component control : controls) {
    if(control instanceof JTextField) {
        System.out.println(control.toString());
        JTextField ctrl = (JTextField) control;
        ctrl.setText("");
    } else if (control instanceof JList) {
        System.out.println(control.toString());
        JList list = (JList) control;
        for (int i = 0; i < list.getModel().getSize(); i++) {
            list.remove(i);
        }
    } else if (control instanceof JTable) {
        System.out.println(control.toString());
        JTable table = (JTable) control;
        for (int i=0;i < table.getRowCount();i++) {
            table.getModel().setValueAt("", i, 0);
        }
        for (int i=0;i < table.getColumnCount();i++) {
            table.getModel().setValueAt("", 0, i);
        }
    } else if (control instanceof JRadioButton) {
        System.out.println(control.toString());
        JRadioButton radio = (JRadioButton) control;
        radio.setSelected(false);
    } else if (control instanceof JPanel) {
        JPanel panel = (JPanel) control;
        controls.addAll(Arrays.asList(panel.getComponents()));
    }
}

0 个答案:

没有答案