2016-11-28 53 views
0

我的問題是當我創建一個繼承自JPanel的類時,爲什麼不使用super.addMouseListener()來添加一個偵聽器?我認爲這種方法是在JPanel的超類中。 這裏是代碼:爲什麼addMouseListener方法不需要超級?

private class DrawPanel extends JPanel 
{ 
    private int prefwid, prefht; 

    // Initialize the DrawPanel by creating a new ArrayList for the images 
    // and creating a MouseListener to respond to clicks in the panel. 
    public DrawPanel(int wid, int ht) 
    { 
     prefwid = wid; 
     prefht = ht; 

     chunks = new ArrayList<Mosaic>(); 

     // Add MouseListener to this JPanel to respond to the user 
     // pressing the mouse. In your assignment you will also need a 
     // MouseMotionListener to respond to the user dragging the mouse. 
     addMouseListener(new MListen()); 
    } 
+0

因爲它是遺傳的 – trooper

回答

2

因爲沒有必要。

您不要在DrawPanel類中聲明方法addMouseListener,因此編譯器會檢查超類的這種方法,並在java.awt.Component中找到它。由於此方法由DrawPanel類繼承,因此可以在此處調用它。

如果你想知道深入的原因,你需要閱讀JLS Sec 15.12, "Method Invocation Expressions"。然而,這不完全是輕讀。

我認爲,關鍵句子是:

Sec 15.12.1

對於類或接口進行搜索,有六種情況需要考慮,具體取決於之前的左括號的形式MethodInvocation:

  • 如果表單是MethodName,即只是一個標識符,那麼:

    • 如果Identifier出現在具有該名稱的可見方法聲明的範圍(§6.3,§6.4.1),則:
    • 如果有一個封閉類型聲明其中該方法是一個構件,讓T成爲最內層的類型聲明。類或接口,以搜索爲T
    • ...

所以TDrawPanel

Sec 15.12.2.1

由編譯時間步驟中確定的類或接口1(§15.12.1)中搜索所有成員方法,這些方法可能適用於這個方法調用;此搜索中包含從超類和超接口繼承的成員。

因此,在DrawPanel及其所有超類中搜索名爲addMouseListener的方法。

+0

它是有道理的。謝謝! – Nat

相關問題