[英]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: 我觉得我在这里错过了一些令人眼花缭乱的东西,这对Java大师来说是如此低调的结果:
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: 尽管JPanel和JMenu都是JComponent的子类,但第一个
instanceof
给出了一个错误:
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
? 为什么我认为我的
JComponent
永远不会是JPanel
?
I suspect you're importing a different JPanel from somewhere. 我怀疑你是从某个地方导入另一个JPanel。 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? 你确定你已经导入了你想要的
JPanel
和JComponent
类吗? 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.