如何在鼠标移动时重新绘制Java SWT应用程序?
我正在尝试编写一个简单的应用程序,在全屏上创建一个透明覆盖,并在我当前的鼠标位置画一条线。这一行应该跟随我的鼠标移动,直到应用程序退出时按下鼠标 我目前在应用程序中遇到无法使用的重画问题,我猜我错放和/或理解了重画应该如何使用 如何正确且高效地重新绘制这样的应用程序 示例代码:如何在鼠标移动时重新绘制Java SWT应用程序?,java,swt,Java,Swt,我正在尝试编写一个简单的应用程序,在全屏上创建一个透明覆盖,并在我当前的鼠标位置画一条线。这一行应该跟随我的鼠标移动,直到应用程序退出时按下鼠标 我目前在应用程序中遇到无法使用的重画问题,我猜我错放和/或理解了重画应该如何使用 如何正确且高效地重新绘制这样的应用程序 示例代码: public class TAGuideLine { static Display display = new Display(); static Shell shell = new Shell(dis
public class TAGuideLine {
static Display display = new Display();
static Shell shell = new Shell(display, SWT.NO_TRIM | SWT.ON_TOP);
public static void main(String[] args) {
shell.setBackground(display.getSystemColor(SWT.COLOR_RED));
shell.setMaximized(true);
shell.setFullScreen(true);
shell.setLayoutData(0);
shell.layout(true, true);
shell.setAlpha(50);
shell.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
System.exit(0);
}
});
shell.addListener(SWT.MouseMove, new Listener() {
public void handleEvent(Event e) {
drawMyLine(MouseInfo.getPointerInfo().getLocation().x,
MouseInfo.getPointerInfo().getLocation().y);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
shell.redraw();
shell.layout();
display.dispose();
}
public static void drawMyLine(int x, int y) {
final GC gc = new GC(shell);
gc.setForeground(display.getSystemColor(SWT.COLOR_GREEN));
gc.setLineWidth(8);
gc.drawLine(x - 250, y - 250, x + 250, y + 250);
gc.dispose();
shell.open();
}
}
要在
Shell
上绘制,通常会添加一个绘制实际图形的绘制侦听器。鼠标事件侦听器将只存储要绘制的坐标,然后在shell上触发重画
下面是代码的草图:
List<Point> points = new ArrayList<>();
shell.addListener( SWT.Paint, new Listener() {
public void handleEvent( Event event ) {
event.gc.setForeground( display.getSystemColor( SWT.COLOR_GREEN ) );
event.gc.setLineWidth( 8 );
for( Point point : points ) {
event.gc.drawLine( point.x - 250, point.y - 250, point.x + 250, point.y + 250 );
}
} );
shell.addListener( SWT.MouseMove, new Listener() {
public void handleEvent( Event event ) {
points.add( MouseInfo.getPointerInfo().getLocation() );
shell.redraw();
}
} );
List points=new ArrayList();
addListener(SWT.Paint,newlistener()){
公共无效handleEvent(事件){
event.gc.setForeground(display.getSystemColor(SWT.COLOR_GREEN));
event.gc.setLineWidth(8);
用于(点:点){
事件gc绘制线(点x-250,点y-250,点x+250,点y+250);
}
} );
shell.addListener(SWT.MouseMove,newlistener()){
公共无效handleEvent(事件){
添加(MouseInfo.getPointerInfo().getLocation());
shell.redraw();
}
} );
类GC
还有一个drawPolyLine()
方法,该方法可能更适合此用例
与您的问题无关,但仍然是:退出应用程序的一种更优雅的方式是使用Shell.dispose()
处理Shell,而不是调用System.exit()