Programming Tutorials

Sample program to draw a rectangle in J2ME

By: Sam Chen in J2ME Tutorials on 2007-09-16  

Here's a sample program to draw a rectangle in J2ME:

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

public class RectangleMIDlet extends MIDlet implements CommandListener {
    private Display display;
    private Command exitCommand;
    private RectangleCanvas canvas;
    public RectangleMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);
        canvas = new RectangleCanvas();

    public void startApp() {

    public void pauseApp() {

    public void destroyApp(boolean unconditional) {

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {

class RectangleCanvas extends Canvas {
    protected void paint(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, 0, w, h);
        g.drawRect(10, 10, w - 20, h - 20);

In this program, we create a RectangleMIDlet class that extends the MIDlet class. This class creates a RectangleCanvas object that extends the Canvas class. In the RectangleCanvas class, we override the paint() method to draw a rectangle using the Graphics class's drawRect() method. We also set the background color using the fillRect() method. Finally, we create a Command object to allow the user to exit the program.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)