Sunday, May 31, 2009

Play with J2ME

j2me

This is an example for graphic test in J2ME. There are 2 files that will be created, MyCanvas.java and scrCanvas.java , have a nice try.

MyCanvas.java script

import javax.microedition.midlet.*;


import javax.microedition.lcdui.*;



public class MyCanvas extends MIDlet implements CommandListener{



private Display display = null;


private scrCanvas scrCanvasObj = null;


private Command exit = new Command("EXIT",Command.EXIT,1);


private Command fullScreen = new Command("Full Screen",Command.OK,1);



public MyCanvas()


{


scrCanvasObj = new scrCanvas();


scrCanvasObj.addCommand(exit);


scrCanvasObj.addCommand(fullScreen);


scrCanvasObj.setCommandListener(this);


}



public void startApp() {


if(display == null)


{


display = Display.getDisplay(this);


display.setCurrent(scrCanvasObj);


}


}




public void pauseApp() {


}



public void destroyApp(boolean unconditional) {


}



public void commandAction(Command c,Displayable d)


{


if(c == exit)


{


notifyDestroyed();


destroyApp(true);


}


else if(c == fullScreen)


{


scrCanvasObj.setFullScreenMode(true);


}


}


}





Di bawah ini script scrCanvas.java



import javax.microedition.lcdui.*;



public class scrCanvas extends Canvas implements Runnable{



private int x = 0,y = 0;


private int ax = 1,ay = 1;



public scrCanvas()


{


Thread thread = new Thread(this);


thread.start();


}



private void backgroundHitam(Graphics g)


{


g.setColor(0x000000);


g.fillRect(0, 0, this.getWidth(), this.getHeight());


}



private void kotak(Graphics g)


{


g.setColor(0xff0000);


g.fillRect(x,y, 25,25);


}



private void tulisString(Graphics g)


{


g.setColor(0x00ff00);


g.drawString("Contoh Canvas", 1, 1, Graphics.LEFT | Graphics.TOP);


}







private void rubahPosisiKotak()


{


x+=ax;


y+=ay;


if(x<=0 || x+25>=this.getWidth())


ax*=-1;


if(y<=0 || y+25>=this.getHeight())


ay*=-1;


}



public void paint(Graphics g)


{


backgroundHitam(g);


tulisString(g);


kotak(g);


}



public void run()


{


while(true)


{


repaint();


rubahPosisiKotak();


try


{


Thread.sleep(1);


}


catch(Exception e)


{


e.printStackTrace();


}


}


}


}



No comments: