Creating the interaction with Canvas

A simple Canvas to demonstrate the capabilities of the LCDUI API.

For more information about using Canvas, see Canvas class specification.

  1. Create the HelloCanvas.java class.

  2. Import the required classes.

    import javax.microedition.lcdui.*;
    
  3. Set HelloCanvas to extend Canvas.

    public class HelloCanvas extends Canvas
    {
  4. Create a new HelloCanvas object for building the yellow screen and red 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();
    	 }
    	
  5. Use this method to color the screen and insert the red 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(0xffff00);
    	 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("CANVAS FONT");
    		 //set the text color
    		 g.setColor(0x00ff0000);
    		 g.setFont(font);
    		 //write the strings in the center of the screen
    		 g.drawString("CANVAS FONT !!!", (w-fontWidth)/2, (h-fontHeight)/2, Graphics.TOP | Graphics.LEFT);
    		 }	
    	 }
    }