我正在寻找一种简单的方法来制作一个Swing组件将所有收到的 事件转发给其父容器(或者甚至所有家长,直至根)。Swing:如何实现从子组件到父容器的所有事件转发?
编辑:
我在哪里需要这个?我有一个图编辑器。组件必须转发按键和 鼠标点击(只要用户单击该组件的子元素 ,就自行设置为“活动”)。
首先,让我介绍一下我现有的解决方案。这是一个解决方法。
public interface IUiAction {
void perform(Component c);
}
public static void performRecursiveUiAction(Container parent, IUiAction action) {
if (parent == null) {
return;
}
for (Component c : parent.getComponents()) {
if (c != null) {
action.perform(c);
}
}
for (Component c : parent.getComponents()) {
if (c instanceof Container) {
performRecursiveUiAction((Container) c, action);
}
}
}
/**
* 1) Add listener to container and all existing components (recursively).
* 2) By adding a ContainerListener to container, ensure that all further added
* components will also get the desired listener.
*
* Useful example: Ensure that every component in the whole component
* tree will react on mouse click.
*/
public static void addPermanentListenerRecursively(Container container,
final IUiAction adder) {
final ContainerListener addingListener = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
adder.perform(e.getChild());
}
};
// step 1)
performRecursiveUiAction(container, adder);
// step 2)
performRecursiveUiAction(container, new IUiAction() {
@Override
public void perform(Component c) {
if (c instanceof Container) {
((Container) c).addContainerListener(addingListener);
}
}
});
}
用法:
addPermanentListenerRecursively(someContainer,
new IUiAction(
@Override
public void perform(Component c){
c.addMouseListener(somePermanentMouseListener);
}
)
);
通过查看代码,你会说这是一个很好的概念?
我目前的概念的问题是:它只转发事件,为其手动指定侦听器。
你能推荐一个更好的吗?
我在某些swing事件上遇到了consume()方法,这个方法用于指示您在处理程序中使用了该事件。我认为相反的是你需要的。 – akarnokd 2009-06-27 14:27:04
例如:鼠标点击,鼠标拖动(“激活”视觉图元素),各种热键,... – 2009-06-27 14:30:20