Alfred Wong's Programming Showcase
About me Links HTML COBOL Java JavaScript Perl PHP
// ITPRG247-IN, Exercise 14_7, p. 601
// 11/12/02 Alfred Wong
// SizePicture.java: Show shrinking and expanding picture from 20x20 to 100x100.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class SizePicture extends JApplet
{
  // Image display panel
  protected PlayImage imagePanel = new PlayImage();

  // Picture to show in image display panel
  protected Image image;

  // Width and height of display area.
  protected int size = 100;

  // Increases or decreases display area by 1 pixel.
  protected int direction = 1;

  // Initialize applet.
  public void init()
  {
    // Load picture.
    image = getImage(getDocumentBase(), "home.gif" );

    // Add image panel to applet.
    getContentPane().add(imagePanel, BorderLayout.CENTER);
  }

  // Override start method in Applet class. Run start in PlayImage class.
  public void start()
  {
    imagePanel.start();
  }

  // Override stop method in Applet class. Run stop in PlayImage class.
  public void stop()
  {
    imagePanel.stop();
  }

  class PlayImage extends JPanel implements ActionListener
  {
    // Fires ActionEvent at fixed rate.
    protected Timer timer;

    // Constructor
    public PlayImage()
    {
      // Set line border on panel.
      setBorder(new LineBorder(Color.red, 1));

      // Create timer with .1 second delay and listener PlayImage
      timer = new Timer(100, this);
    }

    // Superclass SizePicture calls this from start method.
    public void start()
    {
      timer.start();
    }

    // Superclass SizePicture calls this from stop method.
    public void stop()
    {
      timer.stop();
    }

    // This handles Timer ActionEvent every .1 seconds.
    public void actionPerformed(ActionEvent e)
    {
      repaint();

      // Change display area size between 20x20 and 100x100.
      if (size == 20 || size == 100)
      {
        direction = -direction;
      }

      size += direction;
    }

    // Show picture.
    public void paintComponent(Graphics g)
    {
      // Paint background.
      super.paintComponent(g);

      // Draw picture starting in left corner for width and height on this.
      g.drawImage(image, 0, 0, size, size, this);
    }
  }
}
© 2004 Alfred Wong