简体   繁体   中英

Why doesn't instanceof work with JPanel and JComponent?

I feel like I'm missing something blindingly obvious here, so low hanging fruit for a Java guru:

I have code that looks like this:

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

Even though JPanel and JMenu are both subclasses of JComponent, the first instanceof gives an error:

Incompatible conditional operand types JComponent and JPanel

While the second one works fine. Why does it think that my JComponent could never be a JPanel ?

I suspect you're importing a different JPanel from somewhere. For the minute, try using the fully qualified types:

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

Beyond that, I can't think of any reason it wouldn't compile... if you can come up with a short but complete program which demonstrates the problem, that would help. This compiles fine:

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");
        }
    }
}

I would double-check the imports.

Are you sure you've imported the very JPanel and the very JComponent class you wanted? Are they the following?

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

用这个:

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

The following code compiles fine:

import javax.swing.*;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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