gpt4 book ai didi

java - 当在子组件中添加其他 MouseListener 时,父组件的 MouseListener 在子组件内不起作用

转载 作者:行者123 更新时间:2023-11-30 08:21:30 27 4
gpt4 key购买 nike

我有一个 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(...) 也会被调用。< br/>但问题就在这里。当我在 child JPanel 中添加 Listener 时:

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) 方法。
提前致谢。

最佳答案

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

编辑:

现在你正在这样做:

parent.addMouseListener(listenerForParent);

但是你也可以:

parent.addMouseListener(new MyLocalParentMouselistener(listenerForParent));

并实现一个内部类(此处为:MyLocalParentMouselistener),它实现了 MouseListener 并将 MouseListener 作为参数(并保留对它的引用)。在内部,您可以这样做:

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

关于java - 当在子组件中添加其他 MouseListener 时,父组件的 MouseListener 在子组件内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com