将事件传递给父母 [英] Passing events to parent
问题描述
我想创建一个应用程序,其中一些事件应该被处理,就像它们被传递到父容器一样。例如,我有一个包含JLabel的JPanel。顶级的JPanel现在实现了鼠标和拖动。为了使事件看起来像他们到达JPanel而不是标签本身,我需要做些什么。 (更改源对象很重要)
I'd like to create an app where some events are supposed to be handled as if they were delivered to parent containers. For example I've got a JPanel which contains JLabel. The top JPanel implements mousepress and dragging right now. What do I need to do, in order to make the events look like they arrived to JPanel instead of the label itself. (changing source object is important)
有没有比实际实现事件更好的解决方案,并在父代中复制它们? (在一些具有> 5个孩子的对象之后,这将变得乏味)。
Is there some better solution than actually implementing the events and replicating them in the parent? (this would get tedious after some objects with >5 children).
推荐答案
在事件侦听器中,您可以将事件发送到父组件。
At your event listener, you can dispatch the event to the parent component.
正在 myEvent
事件处理函数参数:
Being myEvent
the event handling function argument:
Component source=(Component)myEvent.getSource();
source.getParent().dispatchEvent(myEvent);
但是这个解决方案意味着为要添加的每个元素创建一个新的EventListener。
But this solution implies creating a new EventListener for each element to add.
所以,你可以创建一个单独的事件处理程序并重新使用它,将其添加到所有选定的子项,如下所示:
So, you could create a single event handler and reuse it, adding it to all the chosen children, like this:
final Container parent=this; //we are a the parent container creation code
MouseListener myCommonListener=new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
parent.dispatchEvent(e);
}
@Override
public void mouseEntered(MouseEvent e) {
parent.dispatchEvent(e);
}
@Override
public void mouseExited(MouseEvent e) {
parent.dispatchEvent(e);
}
@Override
public void mousePressed(MouseEvent e) {
parent.dispatchEvent(e);
}
@Override
public void mouseReleased(MouseEvent e) {
parent.dispatchEvent(e);
}
};
JLabel label=new JLabel("This is the first Label");
label.addMouseListener(myCommonListener);
JLabel label2=new JLabel("This is the second Label");
label2.addMouseListener(myCommonListener);
//... and so on
这篇关于将事件传递给父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!