簡體   English   中英

為什么instanceof不能與JPanel和JComponent一起使用?

[英]Why doesn't instanceof work with JPanel and 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
    }
}

除此之外,我無法想到它不會編譯的任何理由......如果你能提出一個簡短但完整的程序來證明這個問題,那將會有所幫助。 編譯好:

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

我會仔細檢查進口。

你確定你已經導入了你想要的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
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM