如何在鼠标移动时重绘Java SWT应用程序?

时间:2015-02-15 20:59:41

标签: java swt

我正在尝试编写一个简单的应用程序,在整个屏幕上创建透明覆盖并在当前鼠标位置绘制一条线。然后该行应该跟随我的鼠标移动,直到应用程序退出时按下鼠标。

我目前在应用程序中重绘的问题不起作用,我想我错过了放置和/或误解了应该如何使用重绘。

如何正确地重绘这样的应用程序并节省资源?

示例代码:

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();
    }
}

1 个答案:

答案 0 :(得分:0)

要在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();
  }
} );

GC也有drawPolyLine()方法,可能更适合此用例。

与您的问题无关,但仍然是:退出应用程序更优雅的方法是使用shell.dispose()处置Shell,而不是调用System.exit()

相关问题