繁体   English   中英

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

[英]Why doesn't instanceof work with JPanel and JComponent?

我觉得我在这里错过了一些令人眼花缭乱的东西,这对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");
        }
    }
}

我会仔细检查进口。

你确定你已经导入了你想要的JPanelJComponent类吗? 它们是以下吗?

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

用这个:

if(javax.swing.JPanel.isInstance(c)){

以下代码编译正常:

import javax.swing.*;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM