//The following two lines are needed to open and close a window. import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; public class MouseBug implements PaintListener, MouseListener { private Shell shell; private Color color; private int x, y; public MouseBug(Shell s, Color c, int initial_x, int initial_y) { shell = s; color = c; x = initial_x; y = initial_y; // Add this MouseBug to the lists of the shell's listeners. shell.addPaintListener(this); shell.addMouseListener(this); } public String toString() { return color + " (" + x + ", " + y + ")"; } public void move(int dx, int dy) { x += dx; y += dy; //A Graphics Context is the brush you paint with. paint(new GC(shell)); } private void paint(GC gc) { gc.setBackground(color); gc.fillRectangle(11 * x, 11 * y, 10, 10); // x, y, width, height } public void paintControl(PaintEvent event) { paint(event.gc); } public void mouseDown(MouseEvent event) { //event.x and event.y are the location in pixels of the event. //xclick and yclick are the location in squares of the event. final int xclick = event.x / 11; final int yclick = event.y / 11; final int dx; final int dy; if (xclick > x) { dx = 1; } else if (xclick < x) { dx = -1; } else { dx = 0; } if (yclick > y) { dy = 1; } else if (yclick < y) { dy = -1; } else { dy = 0; } move(dx, dy); } public void mouseUp(MouseEvent event) { } public void mouseDoubleClick(MouseEvent event) { } public static void main(String[] args) { // The following two lines are needed to open the window. final Display display = new Display(); final Shell shell = new Shell(display); Color black = new Color(display, 0, 0, 0); // rgb MouseBug b = new MouseBug(shell, black, 1, 1); System.out.println(b); // Color red = new Color(display, 255, 0, 0); // Bug b2 = new Bug(shell, red, 2, 2); shell.setText("Volkswagen Bug"); shell.open(); // The following six lines are needed to close the window. while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } black.dispose(); display.dispose(); } }