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();
        canvas.addCommand(exitCommand);
        canvas.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(canvas);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            destroyApp(true);
        }
    }
}

class RectangleCanvas extends Canvas {
    protected void paint(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.setColor(0xffffff);
        g.fillRect(0, 0, w, h);
        g.setColor(0x000000);
        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
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)