I defined a Node class extends Canvas class and handle the mouse event.
public class Node extends Canvas {
String name;
public String getName() { return name; }
public Node(Composite parent, int style, String name) {
super(parent, style);
// TODO Auto-generated constructor stub
this.name = name;
this.setBackground(new Color(Display.getCurrent(), 0, 0, 0));
this.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Mouse up (" + arg0.x + ", " + arg0.y + ") at node " + getName());
}
@Override
public void mouseDown(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Mouse down (" + arg0.x + ", " + arg0.y + ") at node " + getName());
}
@Override
public void mouseDoubleClick(MouseEvent arg0) {
System.out.println("Double click at node " + getName());
}
});
}
and then I created a Composite object and add two Node objects:
Node node1 = new Node(this, SWT.NONE, "node 1");
node1.setBounds(25, 25, 50, 50);
Node node2 = new Node(this, SWT.NONE, "node 2");
node2.setBounds(35, 35, 60, 60);
node2.setBackground(new Color(Display.getCurrent(), 75, 75, 75));
Note that I chose the position of nodes such that they share some common areas. Using color to differentiate between two nodes, I recognized that node1
is shown at the top, while node2
is shown behind. If I apply mouse events in the sharing areas, node1
handle the events and node2
doesn't.
node2
is added to the composite after node1
, so I expected node2
will have the privilege, i.e. if I apply mouse events to sharing areas, node2
should handle the events.
How to fix this problem?
As you can see that the control that is visible (and above the other) gets the mouse events. I think this behavior is correct and expected. I don't suppose you are asking that even though node1
is above node2
and drawn above but still lets node2
receive all the mouse events. Which might not be possible using standard ways.
If however you are asking about ensuring that node2
appears above node1
and thus receives mouse events, you can reverse the creation order, or you can use Control#moveAbove(Control)
like below:
Node node1 = new Node(this, SWT.NONE, "node 1");
node1.setBounds(25, 25, 50, 50);
Node node2 = new Node(this, SWT.NONE, "node 2");
node2.setBounds(35, 35, 60, 60);
node2.setBackground(new Color(Display.getCurrent(), 75, 75, 75));
// Use moveAbove(null) to move node2 above all its siblings
node2.moveAbove(node1);