//The following two lines are needed to open and close a window. import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; //The following two lines are needed to respond to an uncovering. import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; //The following two lines are needed to respond to a keystroke. import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; public class Bug implements PaintListener, KeyListener { private Shell shell; private Color color; private int x, y; public Bug(Shell s, Color c, int initial_x, int initial_y) { shell = s; color = c; x = initial_x; y = initial_y; //Add this bug to the list of the shell's PaintListeners //and to the list of the shell's KeyListeners. shell.addPaintListener(this); shell.addKeyListener(this); } public String toString() { return shell.getText() + " (" + x + ", " + y + ") " + color; } 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 } //This method is called whenever the Bug is exposed. public void paintControl(PaintEvent event) { paint(event.gc); } //This method is called whenever a key is pressed. public void keyPressed(KeyEvent event) { final char c = event.character; if (c == 'h') { move(-1, 0); // left } else if (c == 'j') { move(0, 1); // down } else if (c == 'k') { move(0, -1); // up } else if (c == 'l') { move(1, 0); // right } // Ignore any other keystroke. } public void keyReleased(KeyEvent 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 Bug b = new Bug(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(); } }