2016-11-28 54 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

相关问题