如何在投射之前检查 JComboBox 是哪种类型?
How to check which type a JComboBox is before casting it?
我正在尝试创建一种方法来清除我的 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
现在我所有的组合框都是字符串,所以我不认为它会导致错误(我可能错了),但我仍然想学习正确的方法来做到这一点。
如果我将代码的 Combobox 部分更改为:
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 新手,所以我不了解所有 methods/features。如果我的重置一切的方法可以完成 easier/in 更好的方法,请通知我。我得到了清除网站上另一个 post 的所有字段的原始方法。
怎么样:
if (component instanceof JComboBox) {
JComboBox<?> box = (JComboBox<?>) component;
box.setSelectedIndex(-1);
}
我正在尝试创建一种方法来清除我的 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
现在我所有的组合框都是字符串,所以我不认为它会导致错误(我可能错了),但我仍然想学习正确的方法来做到这一点。
如果我将代码的 Combobox 部分更改为:
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 新手,所以我不了解所有 methods/features。如果我的重置一切的方法可以完成 easier/in 更好的方法,请通知我。我得到了清除网站上另一个 post 的所有字段的原始方法。
怎么样:
if (component instanceof JComboBox) {
JComboBox<?> box = (JComboBox<?>) component;
box.setSelectedIndex(-1);
}