[英]How to redraw a Java SWT app on mouse movement?
I am trying to write a simple app that create a transparent overlay over the full screen and draw a line at my current mouse position. 我正在尝试编写一个简单的应用程序,在整个屏幕上创建一个透明覆盖,并在我当前的鼠标位置画一条线。 This line should then follow my mouse movements until mouse press when the app is to exit.
然后该行应该跟随我的鼠标移动,直到应用程序退出时按下鼠标。
I currently have an issue with redraw in the app that will not work and I guess that I have missplaced and/or missunderstood how the redraw should be used. 我目前在应用程序中重绘的问题不起作用,我想我错过了放置和/或误解了应该如何使用重绘。
How to redraw an application like this correctly and resource efficient? 如何正确地重新绘制这样的应用程序并节省资源?
Sample code: 示例代码:
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();
}
}
To draw on a Shell
you usually add a paint listener that does the actual drawing. 要在
Shell
上绘图,通常会添加一个绘制侦听器来执行实际绘制。 The mouse event listener would just store the coordinates to draw and then trigger a redraw on the shell. 鼠标事件侦听器只存储要绘制的坐标,然后在shell上触发重绘。
Below is a sketch of what the code could look like: 下面是代码的外观草图:
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();
}
} );
Class GC
also has a drawPolyLine()
method that might be more suitable for this use case. GC
类还有一个drawPolyLine()
方法,可能更适合这种用例。
Unrelated to your question but still: a more graceful way to exit the application is to dispose of the Shell with shell.dispose()
instead of calling System.exit()
. 与您的问题无关但仍然是:退出应用程序更优雅的方法是使用
shell.dispose()
而不是调用System.exit()
来处置Shell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.