如何在由子控件制成的 SWT 复合材料上跟踪鼠标? [英] How to track mouse over SWT composite made from sub controls?
问题描述
我创建了自己的控件:
我想跟踪鼠标并添加了一个MouseTrackListener
.不幸的是,MouseEnter
和 MouseLeave
事件也会生成,当鼠标移到我的复合材料的各个部分(即标签和按钮)上时.
I want to track the mouse and added a MouseTrackListener
. Unfortunately MouseEnter
and MouseLeave
events are also generated, when the mouse moves over the parts of my composite (that is the label and the button).
[Mouse enter] - mouse enters the empty space
[Mouse hover] - mouse is over the empty space
[Mouse exit] - mouse moved over label
[Mouse enter] - mouse leaves label and enters empty space
[Mouse hover] - mouse over empty space
[Mouse exit] - mouse leaves composite
如何将复合材料作为一个完整的事物而不是子部分进行跟踪?
How can I track the composite as one complete thing instead of sub parts?
public class MyComposite extends Composite {
public MyComposite(final Composite parent, final int style) {
super(parent, style);
final Label lbl = new Label(this, SWT.NONE);
lbl.setBounds(10, 10, 78, 15);
lbl.setText("My Composite");
final Button btn = new Button(this, SWT.NONE);
btn.setBounds(190, 29, 75, 25);
btn.setText("Ok");
pack();
}
public static void main(final String[] args) {
final Shell shell = new Shell(Display.getDefault());
shell.setText("Testcase");
shell.setLayout(new FillLayout());
final MyComposite comp = new MyComposite(shell, SWT.NONE);
comp.addMouseTrackListener(new MouseTrackListener() {
@Override
public void mouseHover(final MouseEvent e) {
System.out.println("[Mouse hover]");
}
@Override
public void mouseExit(final MouseEvent e) {
System.out.println("[Mouse exit]");
}
@Override
public void mouseEnter(final MouseEvent e) {
System.out.println("[Mouse enter]");
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
推荐答案
如果您只想获得鼠标移动事件,您可以向 Composite
添加一个无类型事件.应该是这样的
If you want to get only mouse move events you can add a untyped event to Composite
. It should be something like
final Composite comp = new Composite(shell, org.eclipse.swt.SWT.NONE);
comp.addListener(SWT.MouseMove, new Listener() {
public void handleEvent(Event event) {
System.out.println("hit");
}
});
如果您将相同的 Listener 实例添加到 MyComposite
的所有子项,则您可以捕获所有鼠标移动事件.
If you add the same Listener instance to all the children of MyComposite
then you can capture all the mouse move events.
或者,您可以使用 Display.addFilter
来捕获所有鼠标事件并过滤发生在您的 Composite
实例或其任何子项上的事件.
Alternately you can use Display.addFilter
to catch all the mouse events and filter if the ones that happen on your Composite
instance or any of its children.
第三种选择是使用 Composite.setCapture
获取鼠标进入 Composite
区域时的所有鼠标事件,并在离开时停止捕获.
A third option is to use Composite.setCapture
to get all mouse events when mouse enters the Composite
area and stop capturing when it leaves.
其中,我认为第一个选项可能是性能最好的.
Out of these I think the first option is probably the best performant.
这篇关于如何在由子控件制成的 SWT 复合材料上跟踪鼠标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!