J2ME Canvas sample to show games programming in J2ME

By: Emiley J. Emailed: 1644 times Printed: 2114 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample J2ME demonstrates the use of Canvas in a midlet. Most of the graphics methods available are used here to let you quickly learn the concepts of graphics programming in J2ME program. It also shows the basics of creating a J2ME game using the controls of a phone. For example handling the left, right keys and the up, down keys etc.
/*
 * @(#)SampleCanvas.java        1.4 01/06/08
 * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
 */

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

class SampleCanvas extends Canvas {
    int     x, y;           // Location of cross hairs
    String  event = "";     // Last key event type
    int     keyCode;        // Last keyCode pressed
    Font    font;           // Font used for drawing text
    int     fh;             // height of the font
    int     w, h;           // width and height of the canvas
    int     titleHeight;    // Height of the title
    int     pieSize;        // Size of the Pie chart used for width and height
    int     barSize;        // Size of the Bar chart used for width and height
    int     eventHeight;    // Size of the event region
    int     pad;            // Padding used between items

    SampleCanvas() {
        w = getWidth();
        h = getHeight();
        font = Font.getFont(Font.FACE_SYSTEM,
	                   Font.STYLE_PLAIN, Font.SIZE_SMALL);
        fh = font.getHeight();

        /* Compute the sizes of the bar and pie charts
         * It should use all the space except for the title
	 * and event regions.
         * Don't let the charts get too small
         */
        pad = 2;
        titleHeight = fh + pad * 2;
        eventHeight = fh * 3;
        barSize = h - (titleHeight + pad) - (eventHeight + pad);
        if (barSize < 20)               // Don't let them get too small
            barSize = 20;
        if (barSize > (w - pad) / 2)    // Shrink to 1/2 width
            barSize = (w - pad) / 2;
        pieSize = barSize;
    }

    protected void keyPressed(int key) {
        keyCode = key;
        event = "Pressed";
        handleActions(key);
        repaint();
    }

    protected void keyRepeated(int key) {
        keyCode = key;
        event = "Repeated";
        handleActions(key);
        repaint();
    }

    protected void keyReleased(int key) {
        keyCode = key;
        event = "Released";
        repaint();
    }

    protected void pointerPressed(int x, int y) {
        this.x = x;
        this.y = y;
        keyCode = 0;
        event = "Pressed";
        repaint();
    }
    protected void pointerReleased(int x, int y) {
        this.x = x;
        this.y = y;
        keyCode = 0;
        event = "Released";
        repaint();
    }

    protected void pointerDragged(int x, int y) {
        this.x = x;
        this.y = y;
        keyCode = 0;
        event = "Dragged";
    }

    void handleActions(int keyCode) {
        int action = getGameAction(keyCode);
        switch (action) {
            case LEFT:
            x -= 1;
            break;
            case RIGHT:
            x += 1;
            break;
            case UP:
            y -= 1;
            break;
            case DOWN:
            y += 1;
            break;
        }
    }

    protected void paint(Graphics g) {

        g.setFont(font);
        g.setGrayScale(255);
        g.fillRect(0, 0, w, h);

        x = (x < 0) ? w - 1 : x;
        y = (y < 0) ? h - 1 : y;
        x = x % w;
        y = y % h;

        // Draw Fill and outline for background of title Text
        int swidth = pad * 2 + font.stringWidth("Pie and Bar Samples");
        int title_x = (w - swidth)/2;

        g.setGrayScale(128);
        g.fillRoundRect(title_x, 0, swidth, fh, 5, 5);
        g.setGrayScale(0);
        g.drawRoundRect(title_x, 0, swidth, fh, 5, 5);

        // Sample Text
        g.setColor(0, 0, 0);
        g.drawString("Pie and Bar Samples", 
	            title_x + pad, pad, Graphics.TOP|Graphics.LEFT);

       // Translate to below title text
        g.translate(0, titleHeight + pad);

        /*
	 * Draw pie chart on the left side
	 * using the barSize for width and height
	 */
        g.setColor(255, 0, 0);
        g.fillArc(0, 0, pieSize, pieSize, 45, 270);
        g.setColor(0, 255, 0);
        g.fillArc(0, 0, pieSize, pieSize, 0, 45);
        g.setColor(0, 0, 255);
        g.fillArc(0, 0, pieSize, pieSize, 0, -45);
        g.setColor(0);
        g.drawArc(0, 0, pieSize, pieSize, 0, 360);

        // Draw Bar chart on right side of the display
        // scale the values to the pieSize maximum value
        int yorig = barSize;
        int h1 = barSize / 3, h2 = barSize / 2, h3 = barSize;
        int avg = (h1 + h2 + h3) / 3;

        // Move over to draw Bar chart
        g.translate((w + pad) / 2, 0);

        int bw = pieSize / 7;
        if (bw < 2)
             bw = 2;
        g.setColor(255, 0, 0);
        g.fillRect(bw*1, yorig-h1, bw+1, h1);
        g.setColor(0, 255, 0);
        g.fillRect(bw*3, yorig-h2, bw+1, h2);
        g.setColor(0, 0, 255);
        g.fillRect(bw*5, yorig-h3, bw+1, h3);
        g.setColor(0);
        g.drawRect(bw*1, yorig-h1, bw, h1);
        g.drawRect(bw*3, yorig-h2, bw, h2);
        g.drawRect(bw*5, yorig-h3, bw, h3);

        // Draw axis for bar chart.
        g.setGrayScale(0);
        g.drawLine(0, 0, 0, yorig);
        g.drawLine(0, yorig, barSize, yorig);
        g.setStrokeStyle(Graphics.DOTTED);
        g.drawLine(0, yorig - avg, barSize, yorig-avg);
        g.setStrokeStyle(Graphics.SOLID);

       // Restore to left and move down
        g.translate(-(w + pad) / 2, pieSize + pad);

        // Draw the key and pointer status
        g.setColor(128, 128, 128);
        int col1 = font.stringWidth("Action:");
        g.drawString("Key: ",      col1,     0,
	            Graphics.TOP|Graphics.RIGHT);
        g.drawString(keyString(keyCode), col1, 0,
	            Graphics.TOP|Graphics.LEFT);
        g.drawString("Action:",    col1,     fh,
	            Graphics.TOP|Graphics.RIGHT);
        g.drawString(actionString(keyCode), col1, fh,
	            Graphics.TOP|Graphics.LEFT);
        g.drawString("Event:",     col1,     fh*2,
	            Graphics.TOP|Graphics.RIGHT);
        g.drawString(event,        col1,     fh*2,
	            Graphics.TOP|Graphics.LEFT);
        int col2 = 80;
        g.drawString("x:",         col2,     0,
	            Graphics.TOP|Graphics.RIGHT);
        g.drawString(Integer.toString(x), col2, 0,
	            Graphics.TOP|Graphics.LEFT);
        g.drawString("y:",         col2,     fh,
	            Graphics.TOP|Graphics.RIGHT);
        g.drawString(Integer.toString(y), col2, fh,
	            Graphics.TOP|Graphics.LEFT);

        // Restore the origin and draw the crosshairs on top
        g.translate(-g.getTranslateX(), -g.getTranslateY());

        g.setColor(0, 0, 0);
        g.drawLine(x, y - 5, x, y + 5);
        g.drawLine(x - 5, y, x + 5, y);
    }
 
    String keyString(int keyCode) {
        if (keyCode == 0) {
            return "";
        }
        return Integer.toString(keyCode);
    }

    String actionString(int keyCode) {
        if (keyCode == 0) {
            return "";
        }

       int action = getGameAction(keyCode);
	switch (action) {
	case FIRE:
	    return "Fire";
	case LEFT:
	    return "Left";
	case RIGHT:
	    return "Right";
	case DOWN:
	    return "Down";
	case UP:
	    return "Up";
	case GAME_A:
	    return "Game A";
	case GAME_B:
	    return "Game B";
	case GAME_C:
	    return "Game C";
	case GAME_D:
	    return "Game D";
	case 0:
	    return "";
	default:
	    return Integer.toString(action);
	}
    }
}

J2ME Home | All J2ME Tutorials | Latest J2ME Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

Hi.
How we can create list with menuitem in canvas?


View Tutorial          By: omid at 2008-09-08 02:09:50
2. View Comment

hello sir , i just implement your code and modify it , but i think there is a problem why are you using translate method because when you updating its origin , the length & width is also increasing or modifying with it , so with your code i am not able to select any icon displayed in ma mobile screen with your code .
so please modify it , because your code is good for a good person and a beginner can not understand or implement it properly , thats my opinion .


View Tutorial          By: tushar at 2012-01-31 05:21:37
3. View Comment

sir there is no startapp(),destroyapp() and pause method how to run the canvas program in netbeans plz help me

View Tutorial          By: Sathish at 2012-08-20 08:49:33

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J.
Error generating R.java from manifest
ERROR 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client
IIS and Tomcat - how to configure to work together
PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......
Adding your own Application icon for your J2ME application (jar file)
Creating Menus in Code using VB.net
Traversing all files in a directory using Ruby
Using Proxy to connect to URLs in Ruby
POST a form in Ruby
Reading URL content using Ruby (HTTP)
dRuby client/server mode sample program
Benchmark module in Ruby
encoding and decoding in Ruby using Base64 Module
Module Abbrev in Ruby
Standard Library Packages in Ruby

More Tutorials in J2ME
Code sample to Send SMS from a J2ME application.
Adding your own Application icon for your J2ME application (jar file)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Datagrams in J2ME (UDP Programming sample)
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
POST UTF-8 encoded data to the server in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Using alerts and tickers in J2ME
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
List of GPRS Access points for all countries

More Latest News
Most Viewed Articles (in J2ME )
List of GPRS Access points for all countries
RMS Basics in J2ME
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
GUI components and menu based J2ME Applications.
Types of Profiles in J2ME
Client Server in J2ME (Socket Programming sample)
Download a file over a network in J2ME midlet
Sample Java program shows how to Read a file over a network using J2ME midlet
Sample J2ME code that shows various functionality of RMS.
DateField sample program in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Sample program to draw a arc in J2ME
J2ME Canvas sample to show games programming in J2ME
Datagrams in J2ME (UDP Programming sample)
Most Emailed Articles (in J2ME)
How to load J2ME applications to the IDEN handsets
POST UTF-8 encoded data to the server in J2ME
Adding your own Application icon for your J2ME application (jar file)
What is J2ME?
Download a file over a network in J2ME midlet
A sample J2ME midlet that shows an example of using a Timer and a TimerTask.
paint() sample program to draw a line in J2ME
What is J2ME?
Y.S. Sun Green Building Research Center
Sample Java program shows how to Read a file over a network using J2ME midlet
Sample program to draw a rectangle in J2ME
translate() Sample program in J2ME
RMS Basics in J2ME
Using List to create a Menu and Menu items in J2ME
Datagrams in J2ME (UDP Programming sample)