java - 为什么 addMouseListener 方法不需要 super ?

标签 java swing mouselistener super

我的问题是,当我创建一个继承自 JPanel 的类时,为什么不使用 super.addMouseListener() 来添加监听器?我认为这个方法位于父类(super class) JPanel 中。 这是代码:

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

最佳答案

因为没有必要。

您没有在 DrawPanel 类中声明方法 addMouseListener,因此编译器会检查父类(super class)中是否有此类方法,并在 java.awt 中找到它.组件。由于此方法是由 DrawPanel 类继承的,因此可以在此处调用它。

如果您想了解更深入的原因,您需要阅读JLS Sec 15.12, "Method Invocation Expressions" 。然而,这并不完全是轻松阅读。

我认为关键的句子是:

Sec 15.12.1

For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:

  • If the form is MethodName, that is, just an Identifier, then:

    • If the Identifier appears in the scope of a visible method declaration with that name (§6.3, §6.4.1), then:
    • If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.
    • ...

所以TDrawPanel

Sec 15.12.2.1

The class or interface determined by compile-time step 1 (§15.12.1) is searched for all member methods that are potentially applicable to this method invocation; members inherited from superclasses and superinterfaces are included in this search.

因此,在 DrawPanel 及其所有父类(super class)中搜索名为 addMouseListener 的方法。

关于java - 为什么 addMouseListener 方法不需要 super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835548/

相关文章:

java - 是否可以远程查看用户的设备?

java - 如何单击 javafx slider

java - 如何使用我的 Java/Android 应用程序进行 SSH?

Java Swing - 如何处理 ActionListener 中的泛型

java - CardLayout 的替代方案不保留对所包含组件的引用

java - 徒手画Java

java - 如何引用已经保存在数据库中的实例?

java - 如何在 JOptionPane 上添加文本区域

java - JPanel 的 addMouseListener

java - mouseEntered 不起作用