Implementazione classe MyCanvas

Listato 7. Implementazione classe MyCanvas

public class MyCanvas extends Canvas
{
    private Image image = null;
    private int width = 0;
    private int height = 0;
    private String lastKeyPressed = "Nessun tasto";
    
    public MyCanvas()
    {
        super();
        try
        {
            image = Image.createImage("/tramonto.png");
            setFullScreenMode(true);
            width = getWidth();
            height = getHeight();
        
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    protected void paint(Graphics g)
    {
        g.setColor(0, 0, 255);
        g.fillRect(0, 0, width, height);
        if (image != null)
        {
            g.drawImage(image, width/2, height/2, Graphics.VCENTER | Graphics.HCENTER);
        }
        g.setColor(255,255,255);
        g.drawString(lastKeyPressed, width/2, height - 10, Graphics.BASELINE | Graphics.HCENTER);
    }
    
    protected void keyPressed(int arg0)
    {
        switch (arg0)
        {
          case KEY_NUM0:
              lastKeyPressed = "0";
          break;
          
          case KEY_NUM1:
              lastKeyPressed = "1";
          break;
          
          case KEY_NUM2:
              lastKeyPressed = "2";
          break;
          
          case KEY_NUM3:
              lastKeyPressed = "3";
          break;
          
          case KEY_NUM4:
              lastKeyPressed = "4";
          break;
          
          case KEY_NUM5:
              lastKeyPressed = "5";
          break;
          
          case KEY_NUM6:
              lastKeyPressed = "6";
          break;
          
          case KEY_NUM7:
              lastKeyPressed = "7";
          break;
          
          case KEY_NUM8:
              lastKeyPressed = "8";
          break;
          
          case KEY_NUM9:
              lastKeyPressed = "9";
          break;
        }
        repaint();
    }
}