A simple Canvas
to demonstrate the capabilities
of the LCDUI API.
For more information about using Canvas
, see Canvas class specification
.
Create the HelloCanvas.java
class.
Import the required classes.
import javax.microedition.lcdui.*;
Set HelloCanvas
to extend Canvas
.
public class HelloCanvas extends Canvas {
Create a new HelloCanvas
object for building the blue screen and white
text. Write the following methods to give functionality to the HelloCanvas
.
boolean myCanvasTXT = true; public HelloCanvas() { }
Create the start
method, and
use the repaint
method to give it a function,
in this case to refresh the screen. For more information, see repaint
in the LCDUI API specification.
The newMessage
method simply changes
its value to false and refreshes the screen with the repaint
method.
void start(){ repaint(); } public void newMessage(){ myCanvasTXT = !myCanvasTXT; repaint(); }
Use this method
to color the screen and insert the white text. The getWidth
and getHeight
methods get the width and height
(in pixels) of the displayable area of the Canvas
. For more information, see getWidth
and getHeight
in the LCDUI API specification. Store the values into integers. Use the setColor
to choose a color value for the instance g
,
and the fillRect
method with your stored integer
values w
and h
to fill the
screen with it. For more information, see setColor
and fillRect
in the LCDUI specification.
public void paint(Graphics g){ int w = getWidth(); int h = getHeight(); g.setColor(0, 51, 240); // blue g.fillRect(0, 0, w, h);
Use the getFont
method to choose a font for your text. Use the Font
class methods getHeight
and stringWidth
to create the dimensions of the text. Choose the color with the setColor
method and set the font with the setFont
. Finally, use the drawString
method to place
and draw your chosen text. For more information, see Font
, getFont
, getHeight
, and drawString
in the LCDUI API specification.
// display the message if (myCanvasTXT){ Font font = g.getFont(); int fontHeight = font.getHeight(); int fontWidth = font.stringWidth("Hello, world!"); // set the text color g.setColor(255, 255, 255); // white g.setFont(font); // write the strings in the center of the screen g.drawString("Hello, world!", (w - fontWidth) / 2, (h - fontHeight) / 2, Graphics.TOP | Graphics.LEFT); } } }