package hello; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Graphics; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class HelloBouncingBall extends MIDlet { int bgColor = 200; protected void startApp() throws MIDletStateChangeException { ICMCanvas myCanvas = new ICMCanvas(); Display myDisplay = Display.getDisplay(this); myDisplay.setCurrent(myCanvas); while (true) { myCanvas.repaint(); } } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub } protected void pauseApp() { // TODO Auto-generated method stub } public class ICMCanvas extends Canvas { int x = 0; int y = 0; int xdir = 1; int ydir = 1; int ballX = 0; int ballY = 0; protected void paint(Graphics g) { if (ballX < 0) { xdir = -xdir; } if (ballY < 0) { ydir = -ydir; } if (ballX > getWidth()) { xdir = -xdir; } if (ballY > getHeight()) { ydir = -ydir; } ballX = ballX + xdir; ballY = ballY + ydir; g.setColor(bgColor); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(200); g.drawRect(x, y, 10, 10); g.setColor(100); g.fillRect(ballX, ballY, 10, 10); } public void keyPressed(int keyCode) { System.out.println("key" + keyCode); if (keyCode == 50) { y--; } if (keyCode == 56) { y++; } if (keyCode == 52) { x--; } if (keyCode == 54) { x++; } repaint(); super.keyPressed(keyCode); } } }