Welcome to the lab

This blog is mostly about mobile game development with Java ME for MIDP 2.0 phones. The tutorials posted here are for the absolute beginner. I hope these tutorials would prove useful to you. Feel free to comment about mistakes and improvements you might discover. Thanks for visiting my blog and have fun learning.

Btw, most of the tutorials here contain instructions for developing MIDlets in NetBeans IDE. But since the code and techniques are the same no matter what IDE you use, you can still follow the coding instructions using the IDE of your choice.

What do you think of my blog? Post your comments here: Post a Comment
Totally forgot about this...
At least this blog is still alive...

Blog and Tutorial Updates
I think I'm almost done with the new blog template which I was somehow inspired to make while playing Company of Heroes. That and I wanted to give the blog little bit more space. The original colors used to be a camouflage scheme since it got burned into my eyes while staring at tanks for a few hours a day. I'll try keep it as neat as possible.

I've also begun updating the old tutorials so readers won't be confused when using the newer NetBeans IDE 6.8. There's just too big a difference between the old versions 5.5 and the latest one that it makes some of the tutorials hard to follow especially when it comes to GUI elements like menu items and the file wizards.

The first few tutorials that rely heavily on the NetBeans IDE GUI have been already updated and ready for newcomers to Java ME programming.

I'm also giving the Chatango flash widget a try as a ShoutBox. It's sitting right there in the left sidebar, underneath the tutorial links. Give it a spin and tell me what you think. Your suggestions, opinions and criticisms are always welcome so don't forget to leave a comment.


Basic Java ME Game Template Part 3
Jump to part: 1 | 2 | 3

In this last part of the tutorial entitled Basic Java ME Game Template, we will modify the code of our MIDlet class create and launch the clsCanvas class the application to run. It is recommended that you start with Part 1 of this tutorial if you haven't done so.


Now open the source code of our MIDlet. We will define a few variables just under the MIDlet declaration.

public class midMain extends MIDlet {
private clsCanvas myCanvas;
public boolean isPaused = false;

...
...


The variable myCanvas will hold an instance of the clsCanvas class. The variable isPaused will tell us if the MIDlet was paused or lost focus. Next, we add some code to the startApp() for launching or starting our main loop and make our clsCanvas object visible.

    public void startApp() {
// check if MIDlet was paused
if (!isPaused){
// initialized only once
// create an instance of clsCanvas
myCanvas = new clsCanvas(this);
// get display
Display d = Display.getDisplay(this);
// make clsCanvas visible
d.setCurrent(myCanvas);
// launch the thread/start main loop
myCanvas.start();
}
//no longer paused
isPaused = false;

}


The Display object is responsible for making objects visible to the screen. In the code above, we retreived the Display object associated with the MIDlet and set the clsCanvas object as the current visible object on the device. We also called the start() method of the clsCanvas object to launch a thread and start our main loop.

Next, we need to modify the pauseApp() method so that our variable "isPaused" will be updated everytime the MIDlet looses focus or minimized into the background by the device.

    public void pauseApp() {
// MIDlet is paused or not the active window
isPaused = true;

}


The last code we will add is for making sure we release all the resources our MIDlet has used and terminate gracefully when your game has ended. Place this code in the destroyApp() method:

        public void destroyApp(boolean unconditional) {
myCanvas = null;
// close MIDlet
notifyDestroyed();

}


Here's the completed midMain.java source code:

package pkgGame;

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

public class midMain extends MIDlet {
private clsCanvas myCanvas;
public boolean isPaused = false;

public void startApp() {
// check if MIDlet was paused
if (!isPaused){
// initialized only once
// create an instance of clsCanvas
myCanvas = new clsCanvas(this);
// get display
Display d = Display.getDisplay(this);
// make clsCanvas visible
d.setCurrent(myCanvas);
// launch the thread/start main loop
myCanvas.start();
}
//no longer paused
isPaused = false;
}

public void pauseApp() {
// MIDlet is paused or not the active window
isPaused = true;
}

public void destroyApp(boolean unconditional) {
myCanvas = null;
// close MIDlet
notifyDestroyed();
}
}


Here's the completed clsCanvas.java source code:

package pkgGame;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

public class clsCanvas extends GameCanvas implements Runnable {
private boolean isRunning = true;
private Graphics g;
private midMain p;

public clsCanvas(midMain parent) {
super(false);
p = parent;
}

public void start(){
// creat a new instance of the Thread class
Thread thread = new Thread(this);
// launch the thread
thread.start();
}

public void run() {
g = getGraphics();
while(isRunning){
// get key state
int iKey = getKeyStates();
// check if FIRE or 5 is pressed
if ((iKey & FIRE_PRESSED) != 0){
// signal an exit
isRunning = false;
}

//set drawing color to black
g.setColor(0x000000);
//fill the whole screen with black
g.fillRect(0, 0, getWidth(), getHeight());
// set drawing color to white
g.setColor(0xffffff);
//display a string
g.drawString("Basic Java ME Game Template", 2, 2, Graphics.TOP | Graphics.LEFT);
//display the key states in white
g.drawString(Integer.toString(iKey), 2, 22, Graphics.TOP | Graphics.LEFT);

flushGraphics();

try{
// make this thread sleep for 30 ms
Thread.sleep(30);
} catch(Exception e){

}
}
// mark as garbage
g = null;
// close the MIDlet
p.destroyApp(true);
p = null;
}

}


Yay! We're done! You can now test your MIDlet by pressing the F6 key on your keyboard or clicking on the Run Main Project icon on the toolbar.

Emulator output : Basic Java ME Game Template


You can download the source code to for this tutorial here : myGame.rar (26.4 Kb)

That ends our tutorial on creating a basic template for your game. I will also be using this template for the rest of the tutorials that will be posted here. If you have some comments, suggestions or having problem with the source code, feel free to leave a comment or use the ShoutBox. Have fun.

Basic Java ME Game Template Part 2
Jump to part: 1 | 2 | 3

We need to make a Java class based on the GameCanvas class. The canvas is where we draw all our stuff like images, sprites, maps, scores so it can be shown on the phone screen. It also let's us know which keys were pressed on the phone so we can respond to them.

A new Java Class file can be created the same way we created a MIDlet in the previous part of this tutorial. Create a new file now by pressing CTRL+N to invoke the "New File" wizard. Choose "Java" from the list of "Categories" and "Java Class" from the list of "File Types" then click on the "Next" button. Alternatively, you can right-click on the package name then choose "New" -> "Java Class".

New File wizard


On the "Name and Location" screen, type in "clsCanvas" for the "Class Name". Make sure to set the "Package" field to the package name we set earlier for our MIDlet in the first part of this tutorial. Click on the "Finish" button when you're done.

Name and Location screen


You should see the source code of class file we just created in the editor panel. If not, then navigate to the file from the project panel and double-click on the filename. Except for the author's name and the file/class/package name (if you chose your own), it should look similar to the code below.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package pkgGame;

/**
*
* @author Devlin
*/
public class clsCanvas {

}


It's now time to turn this class into a GameCanvas class. To do so we just have to modify the class declaration and add the keyword "extends" followed by "GameCanvas" after the class name "clsCanvas".


public class clsCanvas extends GameCanvas{
...
...


While we're doing that, let's also make the clsCanvas implement the Runnable interface. We do this by further adding the keyword "implements" followed by "Runnable" at the end of the class declaration.


public class clsCanvas extends GameCanvas implements Runnable{
...
...


Press CTRL+SHIFT+I (short cut for Fix Imports) to make sure that all the missing import statements required by the code are detected and added automatically. Do this perodically or whenever you add a new class to your code. The clsCanvas class should now look like this:

package pkgGame;

import javax.microedition.lcdui.game.GameCanvas;

public class clsCanvas extends GameCanvas implements Runnable {

}


Now it's time to get rid of those ugly red lines signifying errors in our code. We need to fulfill the requirements of the base class that we are extending and implement the functions of the interface. First, lets add a contructor to our class like so:

public class clsCanvas extends GameCanvas implements Runnable {

public clsCanvas() {
super(false);
}


}


The previous code fullfills the requirements of the GameCanvas class whos constructor takes in a boolean argument. The code inside our constructor means we're passing the value "false" to the constructor of our superclass GameCanvas. Next, the Runnable interface requires us to implement a "run()" method.

public class clsCanvas extends GameCanvas implements Runnable {

public clsCanvas() {
super(false);
}

public void run() {

}


}


Tada! No more errors!

The superclass GameCanvas requires us to implement it's constructor which has one boolean parameter - suppressKeyEvents. Passing the value true stops key events like keyPressed, keyRepeated and keyReleased from being called. But later on we will be rellying more on the function getKeyStates() to find out which keys were pressed whenever we need them. More on this later.

Our canvas class also implements the Runnable interface which allows our game to run on a separate thread. This requires us to implement the run() method which takes no arguments and has no return value. The run() method will contain our main loop and most game related code.

We will now create the main loop for the game. First let's define a private boolean variable which we will use to signal when the loop should end and exit the game. We will call it "isRunning" and place it right under the class declaration.

public class clsCanvas extends GameCanvas implements Runnable {
private boolean isRunning = true;
...
...


We will use a while-loop construct as the main loop for the game using the value of isRunning variable as the looping condition. As mentioned before, we will place it in the run() method.

    public void run() {
while(isRunning){

}
}


Since the initial value of isRunning is "true", the while loop will pretty much run indefinitly until isRunning changes to false. For now, let's make it so that the loop is terminated whenever the FIRE or 5 key is pressed on the phone. We do that by using the getKeyStates() function. We'll also make the thread sleep for a few milliseconds to make sure the game remains responsive to user input using the Thread.sleep() method.

    public void run() {
while(isRunning){
// get keys pressed
int iKey = getKeyStates();
// check if FIRE or 5 is pressed
if ((iKey & FIRE_PRESSED) != 0){
// signal an exit
isRunning = false;
}


try{
// make this thread sleep for 30 ms
Thread.sleep(30);
} catch(Exception e){

}

}
}


The thread sleeps or pauses for 30 milliseconds after each loop. This keeps the the thread from hogging the processing power of the phone and the game from being unresponsive. Without it, the game will not be able to respond to key presses at the moment it needs to. You can change duration of the delay to what you want as long as it works. We will be adding frame limiting at some point and that will dynamically adjust the sleep value and make the frame rate of the game somewhat stable on different phones.

There are two requirements for starting a thread. You need an instance of the Thread class and a object that implements the Runnable interface. We already have an object which implements the Runnable interface so all we just have to make an instance of the Thread class. We will add a start() method to our clsCanvas class that does exactly that. Placed it above the run() method.

    public void start(){
// creat a new instance of the Thread class
Thread thread = new Thread(this);
// launch the thread
thread.start();
}


public void run() {


Let's add some drawing code so we can see what we've done later when we run the application. First let's declare a global variable named "g" that will hold an instance of the Graphics object associated with the GameCanvas class. Place it under the class declaration. Don't forget to press CTRL+SHIFT+I afterwards to add any missing import statements.

public class clsCanvas extends GameCanvas implements Runnable {
private boolean isRunning = true;
private Graphics g;
...
...


We have to initialize it by retreiving the Graphics object from GameCanvas using the getGraphics() function. We will do this right before the while loop inside the run() method.

    public void run() {
g = getGraphics();
while(isRunning){
...
...


While java has a pretty solid garbage collector it still helps if u mark objects as garbage when u no longer need them by assigning a null value. So when we're done using the Graphics object, we'll just set it free ... right under the while loop. While we're at it, we'll just add the rest of the drawing code to the run() method.

    public void run() {
g = getGraphics();
while(isRunning){
// get key state
int iKey = getKeyStates();
// check if FIRE or 5 is pressed
if ((iKey & FIRE_PRESSED) != 0){
// signal an exit
isRunning = false;
}

//set drawing color to black
g.setColor(0x000000);
//fill the whole screen with black
g.fillRect(0, 0, getWidth(), getHeight());
// set drawing color to white
g.setColor(0xffffff);
//display a string
g.drawString("Basic Java ME Game Template", 2, 2, Graphics.TOP | Graphics.LEFT);
//display the key states in white
g.drawString(Integer.toString(iKey), 2, 22, Graphics.TOP | Graphics.LEFT);

// show everything we drew on the screen
flushGraphics();


try{
// make this thread sleep for 30 ms
Thread.sleep(30);
} catch(Exception e){

}
}
// mark as garbage
g = null;

}


One feature of the GameCanvas is an off-screen buffer where everything you draw is first rendered. The contents of this buffer is transferred to the screen after the flushGraphics() function is called. This eliminates flicker and makes your animations smoother. So flushGraphics() is called every time at the end of each loop after you have drawn what you want to be shown on the screen.

The Graphics object contains the methods we must use to draw stuff on the GameCanvas. Just take note that the color passed when setColor() is called will apply to succeeding calls to drawing methods until setColor() is called again with a different color.

Btw, you can find out more about using threads here : Using Threads in J2ME Applications

Before we go to the last part of this tutorial, we need to add a way for the clsCanvas class to tell the MIDlet that the game has ended and the MIDlet needs to close. First, we declare a global variable called "p" to hold a reference to the MIDlet.

public class clsCanvas extends GameCanvas implements Runnable {
private boolean isRunning = true;
private Graphics g;
private midMain p;


Then we modify the clsCanvas constructor so we can pass a reference to the MIDlet when the object is created and assign it to our variable.

    public clsCanvas(midMain parent) {
super(false);
p = parent;
}


Finally, we can call the destroyApp() method of the MIDlet when the main loop ends and close the MIDlet.

        ...
...
// mark as garbage
g = null;
// close the MIDlet
p.destroyApp(true);
p = null;

}


We can now go to the next step: Displaying the GameCanvas.


Basic Java ME Game Template
Jump to part: 1 | 2 | 3

The last tutorial showed you how to use Netbeans IDE to create a basic Java ME MIDlet, compile it, and preview your program in the emulator. Unfortunately, the code generated for the Hello MIDlet is not really suitable for making games that require constant screen updates and lots of animation or movement. This tutorial will show a simple framework that allows you to use lower level drawing functions for making games. The steps that will be taken are as follows:
  • Create an empty Java ME - Mobile Application project.
  • Create the main MIDlet.
  • Create a clsCanvas class which extends the GameCanvas class and implements the Runnable interface.
  • Create the main game loop which will contain all the drawing routines.
  • Launch a worker thread to start and run the main game loop.

Creating the Mobile Application project
First off, open Netbeans IDE and press CTRL+SHIFT+N to create a new project. Choose "Java ME" from the "Categories" list and "Mobile Application" from "Projects" list then click on the "Next" button.

New Project wizard


Change the project name to "myGame". What we need is an empty or blank project so rememeber to uncheck the "Create Hello MIDlet" option before clicking on the "Next" button.

Name and Location screen


On the "Default Platform Selection" screen, choose "DefaultCldsPhone1" for the "Device". Choose "CLDC-1.0" for the "Device Confirguration". Finally, choose "MIDP-2.0" for the "Device Profile" then click on the "Finish" button.

Default Platform Selection screen


You should now be looking at something like this:

The empty project



Creating the Midlet
Now we need to create the MIDlet ourselves. There are several ways to go about this.
  • By pressing CTRL+N on your keyboard.
  • By choosing "New File" from the "File Menu".


  • By right-clicking on the project panel treeview and selecting the "New" item, then clicking on "MIDlet".


For those of you who used one of the first two ways, select "MIDP" from the list of categories and "MIDlet" from the list of file types then click on the "Next" button.


New File wizard


On the "Name and Location" screen, type in "midMain" for "MIDlet Name". The "MIDlet Class Name" field will be automatically filled in for you. Leave the "MIDlet Icon" blank for now. As a rule of thumb, never create your files in the "default package". Enter "pkgGame" in the "Package" field. Click on the "Finish" button.

Name and Location screen


A folder with the same name as the package name you previously entered will be created inside the project source folder where all source code for your game should go.

MIDlet source code


Congratulations!! You have succeeded on creating an empty MIDlet that does absolutely nothing. Next stop, Creating the Canvas...

Your First MIDlet
As I've said in the Getting Started tutorial, we will be using NetBeans IDE in making our applications for Java enabled mobile phones. If you prefer using the Java ME Platform SDK you can still make use of this tutorial but will have to follow a different set of instructions later on. This is because the Java ME Platform SDK doesn't come with the Visual Mobile Designer. No worries, we'll just come back to that later.

In this tutorial we will be creating our first, traditional "Hello World" MIDlet. Why a "Hello World" MIDlet? Because it's very good practice when learning how to program for a platform is to first find out how to make something show up on the screen and the simplest thing to draw on the screen would be text. Although we won't just be drawing text...

"So what's a MIDlet?", you say. Bah! Details...details. Who cares, right? Seriously, in simple terms, a MIDlet is a Java program you can run on mobile devices such as Java enabled cellphones. A MIDlet is to your phone what an "exe" is to a PC (excuse the bad analogy heh).

If you haven't already, open the NetBeans IDE or Java Me Platform SDK. You should see something similar to this:

Netbeans IDE 6.8


Choose "File" from the main menu and click on "New Project" or press CTRL+SHIFT+N. Select "Java ME" from the list of Categories and "Mobile Application" from the list of Projects. Click on the "Next" button.

Choose Project


On the next screen, you get to name your project and choose it's location on your hard drive. As an example I typed "prjTestMidlet" in that box. Be sure to place a check on both "Set as Main Project" and "Create Hello MIDlet" options before you hit the "Next" button.

Name and Location


Leave the "Emulator Platform" to the default one. For "Device", choose "DefaultCldcPhone1". Choose "CLDC-1.0" from "Device Configuration" and "MIDP 2.0" for the "Device Profile". There's more about these settings later but for now hit the "Finish" button.

Default Platform Selection


This is where we will see one of the differences between the Java ME Platform SDK and NetBeans IDE. If all went well, Java ME Platform SDK users should be seeing the source code for the MIDlet that was automatically generated. NetBeans IDE users should be seeing the VMD:

NetBeans IDE 6.8 - Visual Mobile Designer


Java ME Platform SDK 3.0 - Code Editor


Java ME Platform SDK users :
  • Change the "Hello" text into "Name" and the "Hello World!" into your name.
Java ME Platform SDK 3.0 - Edited source code.


NetBeans IDE users :
  • In the VMD window, click on the "Screen" tab if you haven't already.
  • Double click on the text "Hello" and type in "Name : ".
  • Double click on the text "Hello World!" and type in your name.
NetBeans IDE 6.8 - Visually edited form.


By the way, NetBeans IDE users can view the source code of the application by expanding the items of the treeview in the Projects panel.

Click on the "Run Main Project" icon from the toolbar, it's the green "Play" icon or (arrow pointing to the right), or you can just press F6 from your keyboard.

Run Main Project Icon


After it has finished compiling and building the program the emulator window will pop-up. You will immediately see the MIDlet's output on the device emulator's screen. If you have more than one MIDlet in the project you would instead see a menu listing MIDlets on the screen same as on a real phone.

NetBeans IDE 6.8 : Emulator output.


Java ME Platform SDK : Emulator output.


Painless, wasn't it? Now, about those "Default Platform Selection" settings we chose earlier. What you choose will depend on the phone you want your program to run on. Most phones at the time of writing already supports MIDP 2.0 and this in turn allows us to use new libraries that were added to Java ME specifically for multimedia and game development. From here on, the rest of the tutorials you will find here will be focused on MIDP 2.0 phones. You can find more info about MIDP here : Mobile Information Device Profile(MIDP)

The reason that we chose CLDC 1.0 is for compatibility. If you're targeting a specific phone model it's best to view the device specification for that phone from the manufacturers website. One of the more noticeable enhancements included in CLDC 1.1 is that added support for real numbers or floats. Unless you really need to use floats in your code I suggest sticking to CLDC 1.0 for the time being. You can also find resources on the internet on how to deal with floats on the CLDC 1.0 platform. You can find more info about CLDC here : Connected Limited Device Configuration(CLDC)

We chose "DefaultCldcPhone1" for the device to emulate because it has a screen resolution and bit depth commonly seen on phones today. Here's a table showing the different resolutions and bit depth of the default device configurations you can choose from:

Device Resolution Bit Depth Colored Touch Screen
ClamshellCldcPhone1240x32016 bitX-
DefaultCldcJtwiPhone1180x20816 bitX-
DefaultCldcJtwiPhone2180x20816 bitX-
DefaultCldcMsaPhone1240x32016 bitX-
DefaultCldcMsaPhone2240x32016 bitX-
DefaultCldcPhone1240x32016 bitXX
DefaultCldcPhone2240x32016 bitXX
DefaultFxPhone1240x32016 bitXX
DefaultFxTouchPhone1240x32016 bitXX

The device configurations listed above doesn't just define the visual appearance of the emulator but also the optional libraries or packages which extends the emulator's capabilities.

The MIDlet code that was generated for us by the NetBeans IDE or the Java ME Platform SDK is actually a Form based application much like how one would make an application on a PC. You can use this method for creating simple games that don't rely much on fast or continuous screen updates like word games and puzzles. The next set of tutorials will cover the use of lower level drawing routines and a game loop which you can use to make games which require continuous animation or real-time responsiveness like shooters, platformers, driving games, role playing games, etc.

Got a question? I said something completely wrong? Please don't hesitate to leave a comment.