Contoh Program Canvas
MIDLET
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class MenuCanvas extends MIDlet implements CommandListener
{
private Display display;
private Command cmdExit;
private Canvas keyCanvas;
public void startApp()
{
display=Display.getDisplay(this);
cmdExit=new Command("EXIT",Command.EXIT,1);
keyCanvas=new KeyCanvas();
keyCanvas.addCommand(cmdExit);
keyCanvas.setCommandListener(this);
display.setCurrent(keyCanvas);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){}
public void commandAction(Command c, Displayable d)
{
if(c==cmdExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}
CANVAS
import javax.microedition.lcdui.*;
public class KeyCanvas extends Canvas {
private Font mFont;
private String mMessage = "[Press keys]";
private int x=41;
private int y=115;
private static int w,h;
public KeyCanvas() {
mFont = Font.getFont(Font.FACE_PROPORTIONAL,
Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
}
public void paint(Graphics g) {
w = getWidth();
h = getHeight();
// Clear the Canvas.
g.setGrayScale(255);
g.fillRect(0, 0, w - 1, h - 1);
g.setGrayScale(0);
g.drawRect(0, 0, w - 1, h - 1);
g.setFont(mFont);
g.setColor(0,0,200);
g.fillRect(0,0,w,h);
g.setColor(255,255,255);
g.drawRoundRect(x,y,150,70,40,40);
g.drawString("Tugas J2ME Key Canvas",(x+17),(y+28),g.TOP|g.LEFT);
}
protected void keyPressed(int keyCode) {
int gameAction = getGameAction(keyCode);
switch(gameAction) {
case UP:
y=y-8;
if(y<=0)
y=0;
break;
case DOWN:
y=y+8;
if(y>=218)
y=218;
break;
case LEFT:
x=x-8;
if(x<=0)
x=0;
break;
case RIGHT:
x=x+8;
if(x>=89)
x=89;
break;
}
repaint();
}
}
Posting Komentar