Implementing the Canvas

The HelloCanvas class implements a Canvas that displays a colored screen with a message text that can be toggled on and off.

Figure: Colored screen with the message shown (Series 40)

To implement the HelloCanvas class:

  1. Create the HelloCanvas.java class file.

  2. Import the required classes.

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

    public class HelloCanvas extends Canvas {
    
  4. Define a boolean variable for setting the visibility of the message.

        boolean messageVisible = true;
    
  5. Create a new HelloCanvas object for building the colored screen.

        public HelloCanvas() {
        }
    
  6. Create the newMessage method for toggling the message on and off. If the message is visible when this method is called, its visibility is set to false and the HelloCanvas is redrawn without the message. If the message is hidden when this method is called, its visibility is set to true and the HelloCanvas is redrawn with the message. Use the Canvas.repaint method to redraw the HelloCanvas after setting the visibility of the message.

        public void newMessage() {
            messageVisible = !messageVisible;
            repaint();
        }
    
  7. Implement the Canvas.paint method to draw the HelloScreen, that is, to color the screen and write the message text. Use the Canvas.getWidth and Canvas.getHeight methods to retrieve the width and height (in pixels) of the displayable area of the Canvas. Use the Graphics.setColor method to choose a color value for the Graphics object of the paint method, and use the Graphics.fillRect method to fill the Canvas with that color.

        public void paint(Graphics g) {
            int w = getWidth();
            int h = getHeight();
            g.setColor(0, 51, 240); // blue
            g.fillRect(0, 0, w, h);
    
  8. In the paint method, display the message. Use the Font.getFont method to retrieve the font currently used by the Graphics class, and use the Font.getHeight method to retrieve the font height used by the font. Use the Graphics.setColor method to set the color with which to draw the font. Finally, use the Graphics.drawString method to position and draw the message.

            //display the message
            if (messageVisible) {
                Font font = g.getFont();
                int fontHeight = font.getHeight();
                //set the text color
                g.setColor(255, 255, 255); // white
                //write the strings in the center of the screen
                g.drawString("Hello, world!", w / 2, (h - fontHeight) / 2, Graphics.TOP | Graphics.HCENTER);
            }
        }
    
  9. Overwrite the pointerPressed method to toggle the message when Canvas is touched.

        protected void pointerPressed(int x, int y) {
            // Canvas area was touched
            newMessage();
        }
    }