Java 为什么';使用JPanel和JComponent的实例?

Java 为什么';使用JPanel和JComponent的实例?,java,swing,Java,Swing,我觉得我在这里遗漏了一些显而易见的东西,对于一个Java大师来说,这是一个微不足道的成果: 我有如下代码: private static void myFunc(JComponent c) { if (c instanceof JPanel) { //stuff } else if (c instanceof JMenu) { // other stuff } } 尽管JPanel和

我觉得我在这里遗漏了一些显而易见的东西,对于一个Java大师来说,这是一个微不足道的成果:

我有如下代码:

private static void myFunc(JComponent c) {
        if (c instanceof JPanel) {
            //stuff
        }
        else if (c instanceof JMenu) {
            // other stuff
        }
}
尽管JPanel和JMenu都是JComponent的子类,但是的第一个
实例给出了一个错误:

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");
        }
    }
}
import javax.swing.*;

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

我会仔细检查进口货物

你确定你已经导入了你想要的
JPanel
JComponent
类吗? 它们是下面的吗

 import javax.swing.JPanel;
 import javax.swing.JComponent;
使用以下命令:


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

以下代码编译良好:

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");
        }
    }
}
import javax.swing.*;

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

看起来确实是这样。我很好奇我还能导入什么其他的JPanel…谢谢!你正在导入
javax.swing.JPanel
.class
?但是你为什么要这样做呢?是的,如果(javax.swing.JPanel.class.isInstance(c))应该是
{
,这避开了导入问题,并且比
的instanceof
快一点(一个微优化,但为什么不)。