CSC 161 Lab 9-2: Images, and O my, Icons!

Let us take a look at how to use images in Java. We are going to learn how to display images as icons.

Start by downloading the zip file Copy the file to the directory


and unzip it. You should now have a folder named Images in your user directory or home folder.


Icons are little images that put in the user interface. You can use icons on buttons, on labels, and in message dialogs. Icons are represented with an Icon interface. The Icon interface is implemented by a number of classes in the Java libraries. Perhaps the easiest to use is the ImageIcon class.

To create an icon, use one of the constructors for the ImageIcon class:

public ImageIcon(String filename)
public ImageIcon(Image image)

These constructors tell us that to create an icon, you need to have either access to a file containing the image for the icon, or you need to have an Image object. We will see later how to create Image objects. For now, we will start with the constructor that takes as parameter, a file containing the image for the icon. This can be a file with any of the following image types.


To create an icon, use a statement such as the following

        String filename = "/users/gcmuganda/images/car1.jpg";
        Icon icon = new ImageIcon(filename);

Note that I am using forward slashes / rather than the backward slases \ that you normally use in Windows. The filename string specifes a complete path to the file that contains the image to use for the icon. Normally, you would use images that are much smaller than the ones provided for you in the images file. The icons we create will be larger than they should be, but that is Ok for learning purposes.

Icons on Message dialogs

The JOptionPane class has a showMessageDialog method that can take an Icon:

void showMessageDialog(Component parentComponent, Object message, String title,
                              int messageType, Icon icon)

Here is a program that displays an icon in the JOptionPane.

package lab9_2program;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Main
    public static void main(String[] args)
        String filename = "/users/Administrator/images/car1.jpg";
        Icon icon = new ImageIcon(filename);
        JOptionPane.showMessageDialog(null, "Check out my icon!", "Icon Program",
                JOptionPane.INFORMATION_MESSAGE, icon);

Type in an appropriately modified version of this program so it can find the files on your disk, and run the program. You should see a JOptionPane and icon, something like on the right.

Test Your Understanding

Modify the program so that it loops 5 times, each time displaying a different icon if the JOptionPane. Do this by defining a string for the path to the folder containing the image files, and an array of 5 car names. Then, create an array of 5 icons. After that, use a loop that iterates 5 times. At each iteration, create a string representing the name of an image file, and then create an icon for that image and save the icon in an array of Icon objects. You can then display all the icons in a JOptionPane in the same loop, or in a different loop.

        String path = "/users/Administrator/images/";
        String [] carNames = {"car1", "car2", "car3", "car4", "car5"};
        Icon[] myIcons = new Icon[carNames.length];

When you run your program, you should see images such as this one shown on the left

and this one shown on the right.

Test Your Understanding

Look up the documentation page on the JOptionPane class, and find and read up on the following method.

Object showInputDialog(Component parentComponent,  Object message,
                       String title,  int messageType,
                       Icon icon, Object[] selectionValues,
                       Object initialSelectionValue)

This is a very interesting method. Notice that this is an input dialog. In addition to the usual message, type, message type, and icon, this method allows you to specify an array of objects called selectionValues. Basically, this method displays a primitive menu and lets the user pick an item from it. You can also specify an initial selection value. Note that this method returns the object selected by the user.

Create a new project called YourLastNameLab9_2A. Copy your code to this new project. Modify the program so that after it creates the array of 5 icons from the names of the cars, it stores the icons in a map. Each icon will be stored with the name of the car as the key. After that, the program displays an input dialog where the selection values are the names of the 5 cars, and the initial selection value is the name of the first car. The dialog will look like this:

Then, if the user selects car2, say, the program will display a message dialog with the image of car2 in its icon field:

When completed, zip the folder and email to the instructor.

Icons, JLabel and JButton

The constructors for JLabel and JButton allow you to specify a icon.

 JButton(Icon icon)
 JButton(String text, Icon icon)
 JLabel(Icon image)
 JLabel(Icon image, int horizontalAlignment)
 JLabel(String text,  Icon icon, int horizontalAlignment)

In the JLabel constructor, you can specify whether the icon should be aligned to the left, center, or to the right. You do this by specifying one of the values


In addition to the constructors that take Icon parameters, JLabel and JButton have a

void setIcon(Icon defaultIcon)


Test Your Undestanding

Create a new Project called YourLastNameLab9_2B. Modify the program you have been working on so that after it has created an array of icons and stored them in a map, it creates a frame and passes both the array of names of the cars and the icon map as parameters to the constructor. Begin by adding a sixth car to the array of names.

class MyFrame extends JFrame implements ActionListener
    String []carNames;
    MyFrame(String []carNames, Map iconMap)
        // Store the array of car names and the map
        this.carNames = carNames;
        this.iconMap = iconMap;

        setLayout(new GridLayout(2, 3));

        // create 6 buttons and add them to the frame
        // and add the frame as action listener to each button
        // Set the text of each button to the name of a car


    // The action listener adds the image of the car
    // corresponding the text of the button as an icon to the 
    // button
    public void actionPerformed(ActionEvent e)

When the program is first run, it displays a frame like the following:

Then, as the user clicks on the buttons, the icons are added to the buttons:

Important Notice: When completed, zip up the folder and submit by email. Both parts of lab 9-2 are due Friday Week 10 at midnight. Nothing handed in after Friday at midnight will be graded.

This is the last lab for this course. There will be NO new labs assigned next week. However, there will be lab sessions at class time, and the preceptor and I will be present to help you with outstanding labs and projects. If you need help with this lab or any other labs, you NEED TO BE IN LAB Wednesday and Friday.