为什么 instanceof 不能与 JPanel 和 JComponent 一起使用?

2024-05-18

我觉得我在这里错过了一些非常明显的东西,对于 Java 大师来说是很容易实现的目标:

我的代码如下所示:

private static void myFunc(JComponent c) {
        if (c instanceof JPanel) {
            //stuff
        }
        else if (c instanceof JMenu) {
            // other stuff
        }
}

尽管 JPanel 和 JMenu 都是 JComponent 的子类,但第一个instanceof给出错误:

Incompatible conditional operand types JComponent and JPanel

而第二个工作正常。为什么它认为我的JComponent永远不可能成为JPanel?


我怀疑您正在从某个地方导入不同的 JPanel。现在,尝试使用完全限定类型:

private static void myFunc(javax.swing.JComponent c) {
    if (c instanceof javax.swing.JPanel) {
        //stuff
    }
}

除此之外,我想不出它无法编译的任何原因......如果您能想出一个简短但完整的程序来演示该问题,那将会有所帮助。这编译得很好:

import javax.swing.JComponent;
import javax.swing.JPanel;

public class Test {

    public static void myFunc(JComponent c) {
        if (c instanceof JPanel) {
            System.out.println("yes");
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 instanceof 不能与 JPanel 和 JComponent 一起使用? 的相关文章

随机推荐