本文介绍了SWT事件传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测包含多个其他复合材料的复合控件上的点击事件。我试过:

I'm trying to detect click events on a Composite control that contains a number of other composites. I tried:

topComposite.addMouseListener(new MouseListener() {
        ...
        @Override
        public void mouseUp(MouseEvent arg0) {
            logger.info("HERE");
        });
});

但事件永远不会触发。我假设当一个小孩发生一个鼠标事件时,它会传播到链上,但不会发生。如何做到这一点?

But the event never fires. I assumed that when a mouse event occurred on a child it would propagate up the chain but that doesn't happen. How do I do this?

推荐答案

在SWT中,一般规则是事件传播。主要的例外是遍历事件的传播 - 这是很复杂的描述。

In SWT, the general rule is that events do not propagate. The main exception to this, is the propagation of traverse events - which is pretty complicated to describe.

您的问题的简单答案是必须将侦听器添加到 all 你的孩子复合 - 递归

The easy answer to your problem is that you must add the listener to all the children of you Composite - recursively!

例如像这样

public void createPartControl(Composite parent) {
    // Create view...

    final MouseListener ma = new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            System.out.println("down in " + e.widget);
        }
    };
    addMouseListener(parent, ma);
}

private void addMouseListener(Control c, MouseListener ma) {
    c.addMouseListener(ma);
    if (c instanceof Composite) {
        for (final Control cc : ((Composite) c).getChildren()) {
            addMouseListener(cc, ma);
        }
    }
}

点击的小部件是在 e.widget 中找到,如上所示。如果您稍后再添加控件,那么重要的一个问题是再次记住。

The clicked-upon widget is found in e.widget as seen above. An important issue is to remember to do this again if you add more Controls later.

这篇关于SWT事件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:36