为什么instanceof不能与JPanel和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 } } 

除此之外,我想不出有什么理由不能编译…如果你能想出一个简短但完整的程序来certificate这个问题,那会有所帮助。 编译好:

 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。

你确定你已经导入了你想要的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 } } }