Sample program to draw a rectangle in J2ME

By: Sam Chen  

You can draw two kinds of rectangles: regular and rounded. Rectangles, like all geometric drawing, can be drawn in different colors by specifying the color of the graphics pen. 

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Command;

/**
Draws rectangles on a Canvas using the drawing methods
in the javax.microedition.lcdui.Graphics class.
@see javax.microedition.lcdui.Graphics
 
*/
public class RectangleDemo extends Canvas
implements CommandListener
{
// Constant representing the color white.
private static final int WHITE =
0xFF << 16 | 0xFF << 8 | 0xFF;
private Command back = new Command("Back",
Command.BACK,
1);
private Display display =
Display.getDisplay(GraphicsDemo.getInstance());

/**
No-arg constructor. Calls the Canvas no-arg
constructor.
*/
public RectangleDemo()
{
super();
addCommand(back);
setCommandListener(this);
display.setCurrent(this);
}
/**
Paints the clip rectangle white, effectively erasing
whatever was displayed on the Canvas previously.
*/
protected void paintClipRect(Graphics g)
{
int clipX = g.getClipX();
int clipY = g.getClipY();
int clipH = g.getClipHeight();
int clipW = g.getClipWidth();
int color = g.getColor();
g.setColor(WHITE);
g.fillRect(clipX, clipY, clipW, clipH);
g.setColor(color);
}

/**
Paints the look of this Canvas subclass.
*/
public void paint(Graphics g)
{
paintClipRect(g);
int width = getWidth();
int height = getHeight();
int x0 = 5;
int y0 = 5;
int barW = 10;
int initHeight = height - 10;
int deltaH = 10;
g.drawRect(x0, y0, barW, initHeight);
g.fillRect(x0 + barW, y0 + deltaH, barW,
initHeight - deltaH + 1);
g.drawRect(x0 + barW * 2, y0 + deltaH * 2,
barW, initHeight - deltaH * 2);
g.setColor(255, 00, 00);
g.fillRect(x0 + barW * 3, y0 + deltaH * 3,
barW, initHeight - deltaH * 3 + 1);
g.setColor(0, 0, 0);
g.drawRect(x0 + barW * 4, y0 + deltaH * 4,
barW, initHeight - deltaH * 4);
g.fillRect(x0 + barW * 5, y0 + deltaH * 5,
barW, initHeight - deltaH * 5 + 1);
g.drawRect(x0 + barW * 6, y0 + deltaH * 6,
barW, initHeight - deltaH * 6);
g.fillRect(x0 + barW * 7, y0 + deltaH * 7,
barW, initHeight - deltaH * 7 + 1);
}
public void commandAction(Command c, Displayable d)
{
if (c == back)
{
GraphicsDemo.getInstance().display();
}
}
}




Archived Comments

1. Hello! Would you mind if I share your blog with my myspace group?

There's a lot of fo

View Tutorial          By: anyoption strategie at 2016-05-25 13:45:10


Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)

Comment on this tutorial