有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在强制转换JComboBox之前检查其类型?

我正在尝试创建一种方法来清除JFrame中的所有字段。但是我遇到了来自Eclipse的警告

private void clearAll(Container container) {

        for (Component component : container.getComponents()) {
            if (component instanceof JTextField) {
                JTextField field = (JTextField) component;

                field.setText("");
            }

            if (component instanceof JComboBox) {
                JComboBox<String> box = (JComboBox<String>) component;
                box.setSelectedIndex(-1);
            }

            if (component instanceof Checkbox) {
                Checkbox box = (Checkbox) component;

                box.setState(false);
            }

            if (component instanceof Container) {
                clearTextFields((Container) component);
            }
        }
    }

但我得到的警告是:

Type safety: Unchecked cast from Component to JComboBox

现在我所有的组合框都是字符串,所以我不认为它会导致错误(我可能错了),但我仍然想学习正确的方法来做到这一点

如果我将代码的组合框部分更改为:

    if (component instanceof JComboBox) {
                JComboBox box = (JComboBox) component;
                box.setSelectedIndex(-1);
            }

我收到一条不同的警告信息:

JComboBox is a raw type. References to generic type JComboBox should be parameterized

我是swing新手,所以我不知道所有的方法/特性。如果我重置一切的方法可以更容易/更好地完成,请通知我。我得到了从站点上的另一个帖子中清除所有字段的原始方法


共 (1) 个答案

  1. # 1 楼答案

    那么:

       if (component instanceof JComboBox) {
            JComboBox<?> box = (JComboBox<?>) component;
            box.setSelectedIndex(-1);
       }