Site icon FahmidasClassroom

Simple animation using Java ImageIcon

Animation1

The use of simple animation using Java ImageIcon class has been shown in this tutorial. A simple opening and closing mailbox application has been implemented here. You will require two images to see the output of the application. Follow the steps to create 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 two 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 p1.png image by using the Icon property of the label. Set “Open Mailbox” as button caption.

Step-4:

Import the following package.

import javax.swing.ImageIcon;

Step-5:

Add the following lines after the class declaration that will define two imageIcon objects and an integer variable to set the image on the label.

ImageIcon image0 = new ImageIcon(getClass().getResource(“p2.png”));
ImageIcon image1 = new ImageIcon(getClass().getResource(“p1.png”));
int pictureNumber = 1;

Step-6:

Double clicks on the button and add the following code on the opened method.

if (pictureNumber == 0)
        {

            jLabel1.setIcon(image1);
            pictureNumber = 1;
            jButton1.setText("Open Mailbox");
        }
        else
        {
            jLabel1.setIcon(image0);
            pictureNumber = 0;
            jButton1.setText("Close Mailbox");
        }

Step-7:

Save the file and run the file.

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

Exit mobile version