Programming Tutorials

translate() Sample program in J2ME

By: Baski in J2ME Tutorials on 2007-09-17  

The translate() method in J2ME is used to move the origin of the graphics context to a new location, specified by the given x and y coordinates. Once the origin has been translated, all subsequent drawing operations are performed relative to the new origin.

Here is an example program that demonstrates the use of the translate() method to draw a rectangle at a specific position in J2ME:

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

public class TranslateDemo extends MIDlet {
    private Display display;

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

    public void startApp() {
        Canvas canvas = new Canvas() {
            protected void paint(Graphics g) {
                // Set the color to blue
                g.setColor(0, 0, 255);

                // Draw a rectangle at (50,50)
                g.drawRect(50, 50, 50, 50);

                // Translate the graphics context to (100,100)
                g.translate(50, 50);

                // Set the color to red
                g.setColor(255, 0, 0);

                // Draw another rectangle at (0,0)
                g.drawRect(0, 0, 50, 50);


    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

In this program, we first set the color to blue and draw a rectangle at position (50,50) using the drawRect() method. We then use the translate() method to move the origin of the graphics context to position (100,100) and set the color to red. Finally, we draw another rectangle at the new origin using the drawRect() method.

When the program is run, the first rectangle is drawn in blue at position (50,50) and the second rectangle is drawn in red at position (150,150) (i.e., (100+50,100+50)).

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)