FahmidasClassroom

Learn by easy steps

Animation2

Java Timer is a very useful package to implement time related applications. A simple animation application using timer object has been shown in this application. Follow the steps to implement the application.

Pre-requisites:

1. Install the latest version of JDK.

2. Install the NetBeans editor

Steps-1:

Create a new Java project named animation without class.

Step-2:

Download the following images and store in the src folder of the project folder.

Step-3:

Add a class with a JFrame. Add a label and a button in the form. Add earth1.png image by using the Icon property of the label. Set “Start” as button caption.

Step-4:

Import the following packages into the aplication.


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.Timer;

Step-5:

Add the following lines after the class declaration to set images using ImangeIcon objects.

ImageIcon image1 = new ImageIcon(getClass().getResource("earth1.png"));
ImageIcon image2 = new ImageIcon(getClass().getResource("earth2.png"));
ImageIcon image3 = new ImageIcon(getClass().getResource("earth3.png"));
ImageIcon image4 = new ImageIcon(getClass().getResource("earth4.png"));
ImageIcon image5 = new ImageIcon(getClass().getResource("earth5.png"));
ImageIcon image6 = new ImageIcon(getClass().getResource("earth6.png"));
Timer earthTimer;
int pictureNumber = 1;

Step-6:

Add the following lines to the constructor method.

earthTimer = new Timer(500, new ActionListener()
{
     @Override
     public void actionPerformed(ActionEvent e)
     {
          earthTimerActionPerformed(e);
     }
});

Step-7:

Add the following code to implement earthTimerActionPerformed() method.

private void earthTimerActionPerformed(ActionEvent e)
{
        switch (pictureNumber)
        {
            case 1:
            jLabel1.setIcon(image1);
            break;
            case 2:
            jLabel1.setIcon(image2);
            break;
            case 3:
            jLabel1.setIcon(image3);
            break;
            case 4:
            jLabel1.setIcon(image4);
            break;
            case 5:
            jLabel1.setIcon(image5);
            break;
            case 6:
            jLabel1.setIcon(image6);
            break;
        }
        pictureNumber++;
        if (pictureNumber == 6)
        {
            pictureNumber = 0;
        }
}

Step-8:

Double clicks on the button and add the following codes.

// toggle timer and button text
if (earthTimer.isRunning())
{
      earthTimer.stop();
      jButton1.setText("Start");
}
else
{
      earthTimer.start();
      jButton1.setText("Stop");
}

Step-9:

Save the file and run the application.

Reference: Learn Java™ GUI Applications, A JFC Swing NetBeans Tutorial