Programming Tutorials

paint() sample program to draw a line in J2ME

By: Reema sen in J2ME Tutorials on 2007-09-16  

Here is a sample program to draw a line using paint() method in J2ME:

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

public class LineMidlet extends MIDlet {
    private Display display;

    public LineMidlet() {
        display = Display.getDisplay(this);

    public void startApp() {
        display.setCurrent(new LineCanvas());

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    private class LineCanvas extends Canvas {
        protected void paint(Graphics g) {
            int width = getWidth();
            int height = getHeight();

            g.setColor(255, 0, 0); // set color to red
            g.drawLine(0, 0, width, height); // draw a line from (0,0) to (width,height)

In this program, we create a LineMidlet class that extends MIDlet and implements the methods startApp(), pauseApp(), and destroyApp(). In the constructor, we get the Display object. In startApp(), we set the current display to a new instance of LineCanvas. LineCanvas is a nested class that extends Canvas. In the paint() method of LineCanvas, we get the width and height of the canvas using getWidth() and getHeight() methods. We set the color to red using the setColor() method, and draw a line using the drawLine() method. The line goes from (0,0) to (width,height), which will create a diagonal line across the canvas.

When you run this program, you should see a red diagonal line on the screen.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)