这通常很难解决,因为在 draw2d 中鼠标事件不会像在 html 中那样通过元素传播。
例如,您可以将侦听器移动到画布上:
import org.eclipse.draw2d.ActionEvent;
import org.eclipse.draw2d.ActionListener;
import org.eclipse.draw2d.Border;
import org.eclipse.draw2d.Button;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.Layer;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.ScalableLayeredPane;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class HHH {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell();
shell.setLayout(new FillLayout());
final FigureCanvas canvas = new FigureCanvas(shell);
final ScalableLayeredPane pane = new ScalableLayeredPane();
pane.setScale(1.5f);
canvas.setContents(pane);
final Layer layer = new Layer();
layer.setLayoutManager(new XYLayout());
pane.add(layer);
final Figure container = new Figure();
container.setOpaque(true);
container.setBackgroundColor(ColorConstants.lightBlue);
container.setLayoutManager(new XYLayout());
layer.add(container, new Rectangle(100, 100, 100, 100));
final Button b = new Button("Push");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
MessageBox box = new MessageBox(shell);
box.setText("button pressed");
box.open();
}
});
container.add(b, new Rectangle(10, 10, -1, -1));
canvas.addMouseMoveListener(new MouseMoveListener() {
Border oldBorder = null;
boolean over = false;
@Override
public void mouseMove(org.eclipse.swt.events.MouseEvent e) {
final Rectangle containerBounds = container.getBounds().getCopy();
container.translateToAbsolute(containerBounds);
if (containerBounds.contains(e.x, e.y)) {
// simulate enter container figure
if (!over) {
oldBorder = container.getBorder();
container.setBorder(new LineBorder());
over = true;
}
} else {
// simulate exit container figure
if (over) {
container.setBorder(oldBorder);
oldBorder = null;
over = false;
}
}
}
});
shell.setSize(500, 500);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}