Swing: How to achieve forwarding of all events from subcomponents to parent container?

I'm looking for a straightforward way to make a **Swing component forward all received events to its parent container** (or even all parents up to root). **EDIT**: Where do I need this? I have a diagram editor. Components must forward key press and mouse clicks (to set themselves as "active" as soon as the user clicks a subelement of that component). First, let me present my existing solution for this. It's a bit of a workaround. 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); } } }); } Usage: addPermanentListenerRecursively(someContainer, new IUiAction( @Override public void perform(Component c){ c.addMouseListener(somePermanentMouseListener); } ) ); By looking over the code, would you say it's a good concept? The problem with my current concept is: It's forwarding only events, for which a listener was specified manually. Can you suggest a better one?
I encountered the consume() method on some swing events which is used to indicate you consumed the event in your handler. I think the opposite is what you need.

以上就是Swing: How to achieve forwarding of all events from subcomponents to parent container?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准