【发布时间】:2010-11-06 09:02:42
【问题描述】:
我正在寻找一种直接的方法来使 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);
}
)
);
通过查看代码,您认为这是一个好概念吗?
我当前概念的问题是:它仅转发事件,为此手动指定了侦听器。
你能推荐一个更好的吗?
【问题讨论】:
-
我在一些摇摆事件上遇到了consume() 方法,该方法用于指示您在处理程序中消费了该事件。我认为你需要的恰恰相反。
-
例如:鼠标点击、鼠标拖动(“激活”可视化图表元素)、各种热键……
标签: java user-interface swing events