我刚刚开始学习swt,我正在尝试做一个我在课程中看到的例子并且它不起作用 - 它应该围绕鼠标的尖端创建一个圆圈并随身携带 但圆圈不在正确的位置 - 他用鼠标移动但不在它的尖端
这是代码:
import java.awt.MouseInfo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class CanvasKeyEvent {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(370, 380);
final Canvas c=new Canvas(shell,SWT.NONE);
c.setSize(370,380);
c.setLocation(21, 21);
c.addPaintListener(new Example());
c.addMouseMoveListener(new MouseMoveListener(){
public void mouseMove(MouseEvent e) {
c.redraw();
}
});
shell.open();
while(!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
static class Example implements PaintListener {
@Override
public void paintControl(PaintEvent e) {
int x = MouseInfo.getPointerInfo().getLocation().x;
int y = MouseInfo.getPointerInfo().getLocation().y;
e.gc.drawOval(x , y , 20 , 20);
}
}
}
有人知道它为什么不能正常工作?
谢谢
答案 0 :(得分:0)
最好不要将java.awt.MouseInfo
与SWT一起使用 - 首选Display.getCurrent().getCursorLocation()
。
您遇到的主要问题是找到相对于Canvas的鼠标位置。尝试这样的事情:
public void paintControl(PaintEvent e) {
Canvas c = ((Canvas) e.getSource());
Point pos = c.toDisplay(c.getLocation());
Point relativePos = new Point(e.x - pos.x, e.y - pos.y);
int x = Display.getCurrent().getCursorLocation().x + relativePos.x + 10;
int y = Display.getCurrent().getCursorLocation().y + relativePos.y + 10;
e.gc.drawOval(x, y, 20, 20);
}