2

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?

Morinar
  • 3,460
  • 8
  • 40
  • 58

4 Answers4

6

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");
        }
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That does indeed appear to be the case. Curious what other JPanel I could possibly be importing... Thanks! – Morinar May 05 '11 at 21:55
1

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;
Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106
1

Use this:

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

Femi
  • 64,273
  • 8
  • 118
  • 148
1

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
    }
  }
}
Oswald
  • 31,254
  • 3
  • 43
  • 68