Berikut ini adalah coding untuk membuat program Kapal Laut dengan J2ME


CODING

import javax.microedition.lcdui.*;
import java.io.IOException;

public class MainCanvas extends Canvas implements Runnable, CommandListener{

private Display display;
private KapalLaut midlet;

private Image image;

int x = 0;
int y = 0;

int xKotak;
int yKotak;

Command cmdNewGame = new Command("New game", Command.SCREEN, 1);
Command cmdExit = new Command("Exit", Command.SCREEN, 1);

String keterangan = "";
String c = "";

private boolean kiri = false;
private boolean kanan = true;

public MainCanvas(KapalLaut midlet, Display display){

this.midlet = midlet;
this.display = display;

xKotak = getWidth()/2 - 5;
yKotak = getHeight() - 10;

addCommand(cmdNewGame);
addCommand(cmdExit);

setCommandListener(this);

try{
image = Image.createImage("/pyg.jpg");
}
catch(IOException ioe){
}

}

public void paint(Graphics g){
g.setColor(255,255,255);
g.fillRect(0, 0, getWidth(), getHeight());

g.drawImage(image, x, y, Graphics.TOP | Graphics.LEFT);

g.setColor(255,0,0);
g.fillRect(xKotak, yKotak, 10, 10);

g.setColor(0,0,0);
g.drawString(keterangan, getWidth()/2-20, getHeight()/2, Graphics.TOP | Graphics.LEFT);
g.drawString(c, 0, 0, Graphics.TOP|Graphics.LEFT);

}

public void commandAction(Command c, Displayable d){

if (c == cmdNewGame){
midlet.startApp();
}
if (c == cmdExit){
midlet.exitMIDlet();
}

}
public void keyPressed(int keyCode){

if (keyCode == KEY_NUM1){
kiri = true;
kanan = false;
}

if (keyCode == KEY_NUM3){
kiri = false;
kanan = true;
}

}


public void run(){

while(y <= (getHeight() - 60)){ try{ Thread.sleep(100); } catch(InterruptedException ie){ } if ((kiri) && (x > 0)){
x = x - 10;
}
else if ((kanan) && (x < (getWidth() - 60))){ x = x + 10; } y = y + 5; repaint(); } if (((x+23) >= xKotak) && (x+23 <= xKotak+13)){ keterangan = "Kapal Laut Aman"; c = "kapal laut"; } else{ keterangan = "Kapal Laut Karam"; try{ Thread.sleep(100); } catch(InterruptedException ie){ } y = y + 5; } repaint(); } } Program J2ME Kapal Laut

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class KapalLaut extends MIDlet{

private Display display;
private MainCanvas mainCanvas;

public KapalLaut(){

display = Display.getDisplay(this);

}

public void startApp(){

mainCanvas = new MainCanvas(this, display);
display.setCurrent(mainCanvas);

new Thread(mainCanvas).start();

}

public void pauseApp(){
}

public void destroyApp(boolean unconditional){
}

public void exitMIDlet(){

destroyApp(false);
notifyDestroyed();

}

}

1 comments:

Post a Comment

What time is it?

About Me

My photo
Pekanbaru, Riau, Indonesia

My Timeline

Follow aaimm on Twitter

Blog List

Followers

Blogger Bertuah