Programming Tutorials

Sample program to draw text in J2ME

By: Abinaya in J2ME Tutorials on 2007-09-16  

Here's a sample program in J2ME to draw text with different options and available methods:

import javax.microedition.lcdui.*;

public class TextCanvas extends Canvas {

    private String text = "Hello World!";
    private int xPos = 0;
    private int yPos = 0;

    protected void paint(Graphics g) {
        g.setColor(0, 0, 255);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(255, 255, 255);
        g.drawString(text, xPos, yPos, Graphics.TOP | Graphics.LEFT);
    }

    public void keyPressed(int keyCode) {
        switch (getGameAction(keyCode)) {
            case Canvas.LEFT:
                xPos -= 10;
                break;
            case Canvas.RIGHT:
                xPos += 10;
                break;
            case Canvas.UP:
                yPos -= 10;
                break;
            case Canvas.DOWN:
                yPos += 10;
                break;
        }
        repaint();
    }
}

This program creates a canvas and sets the background color to blue. It then draws a white string at a specified location (xPos, yPos) with the text "Hello World!" using the drawString() method. The keyPressed() method is used to move the text around based on arrow key input. The available methods for drawing text include drawString(), drawSubstring(), drawChar(), drawChars(), setFont(), and setColor(). The Graphics constants TOP, BOTTOM, LEFT, RIGHT, and BASELINE can be used to specify the alignment of the text.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)