// Demo for Painting and Event handling
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PaintingApplet extends Applet 
  {
    // Global toggle which the event listener sets and paint() uses.
    private boolean toggle;

    public void init () 
      {
        setForeground(Color.white);
        setBackground(Color.lightGray);
        // Add event listener
        addMouseListener(new MouseAdapter() 
          {
            public void mouseClicked(MouseEvent e) 
              {
                // Toggle to change the text color
                toggle = !toggle;
                // Update the screen
                repaint(); 
              }
          });
      }

    public void paint (Graphics g) 
      {
        // Translate the origin
        g.translate(getInsets().left, getInsets().top);
        // Draw oval in foreground color of the applet
        g.fillOval(0, 0, getBounds().width, getBounds().height);
        // Info that is governed by the event handler.
        // Only changed if toggled by the event handler.
        if (toggle) 
          {
            // Set the color and draw the string.
            g.setColor(Color.black);
            String str = "Beware the Mouse Catcher!";
            FontMetrics metrics = g.getFontMetrics();
            int stringWidth = metrics.stringWidth(str);
            g.drawString(str,                 // Center the string
                         Math.max(0,(getBounds().width - stringWidth))/2,
                         getBounds().height/2);
          }
      }

    // Override update() to reduce flickering
    public void update(Graphics g) 
      {
        // Do the painting
        paint(g);
      }
  }
