【问题标题】:MouseListener of parent component is not working inside child component when other MouseListener added in child当在子组件中添加其他 MouseListener 时,父组件的 MouseListener 在子组件中不起作用
【发布时间】:2014-09-30 20:30:40
【问题描述】:

我有一个 JPanel parent 和一个 JPanel child。我在父级中添加了一个 MouseListener,在子级中添加了另一个。代码如下:

public void init(MouseListener listenerForParent, MouseListener listenerForChild)
{
    JPanel parent = new JPanel("Parent");
    JPanel child = new JPanel("Child");
    parent.add(child);
    parent.addMouseListener(listenerForParent);
    ...
}

到目前为止一切正常。 当我单击时,listenerForParentmouseClicked(...) 正在调用 我正在接收上述代码的事件,即使我单击 child JPanel,也会调用 listenerForParentmouseClicked(...)
但问题就在这里。当我在child JPanel 中添加监听器时:

public void init(MouseListener listenerForParent, MouseListener listenerForChild)
{
    JPanel parent = new JPanel("Parent");
    ...
    parent.addMouseListener(listenerForParent);
    child.addMouseListener(listenerForChild); // added new line i.e. adding MouseListener in child
}

现在,当我单击 child JPanel 区域时,只有 listenerForChildmouseClicked(...) 正在调用。
是否可以在两个侦听器中获取事件。

在哪里,我无法修改给定的 MouseListeners。 即我无法更改 mouseClicked(...),因为它是由我没有来源的其他类提供给我的。因此我不能使用dispatchEvent(AWTEvent e) 方法。
提前致谢。

【问题讨论】:

    标签: java swing events awt mouseevent


    【解决方案1】:

    你不能修改它,但你可以包装它。您可以将其放入您自己的 MouseListener 本地实现中,然后执行您必须做的事情,然后调用传入的鼠标侦听器。

    编辑:

    现在你正在这样做:

    parent.addMouseListener(listenerForParent);
    

    但你也可以:

    parent.addMouseListener(new MyLocalParentMouselistener(listenerForParent));
    

    并实现一个内部类(此处为:MyLocalParentMouselistener),该类实现 MouseListener 并将 MouseListener 作为 Argument(并保留对它的引用)。 在里面,你可以这样做:

    mouseClicked( MouseEvent e ){
    
        // Do some stuff here
    
        // assume we kept a reference to the passid-in mouseListener from 3rd Party class
        // in a class variable called "passedInMouseListenerInstance"
        passedInMouseListenerInstance.mouseClicked(e);
    }
    

    您现在可以对 Child 执行相同的操作,并传递两个侦听器并调用它们,如果这是您所期望和想要的。

    希望现在更清楚了。

    这里是写MouseListeners的教程:http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

    【讨论】:

    • 对不起,我没明白你的意思。我只从一个类中获取 MouseListeners,即 listenerForParentlistenerForChild,我没有该类的源代码。
    • 你不需要有父监听器的源代码。即使您没有源代码,您也可以创建父级侦听器的新实例。或者,您可以使用父级的 getMouseListeners 并从 clild 调用每个侦听器。
    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2022-07-21
    • 2019-05-26
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多