Displaying image in Java

In this tutorial, we show how to display an image in Java. We show how to build a project using command line tools, Ant, Maven, NetBeans, and Eclipse. The source code and the image are available at the author's Github repository.

Beginner programmers often have problems with displaying an image in a project. The problem lies in correctly identifying the path to the image file. The key part is to realize that the relative path to the image file starts from the project directory. This tutorial was created to make things clear.

The following example shows the screenshot of the application.

Displaying image in Java
Figure: Displaying image in Java

The source code

Here we provide the source code for displaying an image in Java.

DisplayImage.java
package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DisplayImage extends JFrame {
    
    public DisplayImage() {

        initUI();
    }

    private void initUI() {       
        
        ImageIcon ii = loadImage();

        JLabel label = new JLabel(ii);

        createLayout(label);

        setTitle("Image");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private ImageIcon loadImage() {

        ImageIcon ii = new ImageIcon("src/images/snake.jpg");
        return ii;
    }

    private void createLayout(JComponent... arg) {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
        );

        gl.setVerticalGroup(gl.createParallelGroup()
                .addComponent(arg[0])
        );

        pack();
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            DisplayImage ex = new DisplayImage();
            ex.setVisible(true);
        });
    }
}

The example creates a Java Swing application and uses an ImageIcon component to display the image.

private ImageIcon loadImage() {

    ImageIcon ii = new ImageIcon("src/images/snake.jpg");
    return ii;
}

The important part is here. The ImageIcon takes the file path to the image. This file path depends on the build tool we use.

Displaying image with command line tools

The first example builds the Java application with command line tools.

$ mkdir bin
$ mkdir -p src/main/com/zetcode/
$ mkdir src/main/images
$ cp ~/Pictures/snake.jpg src/main/images/

We create the project structure and copy the image to the images directory.

private ImageIcon loadImage() {

    ImageIcon ii = new ImageIcon("src/main/images/snake.jpg");
    return ii;
}

In a command line application, we have used the src/main/images/snake.jpg path.

$ tree
.
├── bin
└── src
    └── main
        ├── com
        │   └── zetcode
        │       └── DisplayImage.java
        └── images
            └── snake.jpg

6 directories, 2 files

This is how the project directory structure looks like.

$ javac -d bin src/main/com/zetcode/DisplayImage.java 

The application is compiled with the javac tool.

$ tree
.
├── bin
│   └── com
│       └── zetcode
│           └── DisplayImage.class
└── src
    └── main
        ├── com
        │   └── zetcode
        │       └── DisplayImage.java
        └── images
            └── snake.jpg

8 directories, 3 files

After compiling the source code, we have a Java class file created in the bin/com/zetcode subdirectory.

$ java -cp bin com.zetcode.DisplayImage 

We run the application with the java command.

Using Ant to build the project

In this section, we use the Ant build tool to create the project.

$ mkdir -p src/main/com/zetcode/
$ mkdir src/main/images
$ cp ~/Pictures/snake.jpg src/main/images/

We create the directories and copy the image file.

$ tree
.
├── build.xml
└── src
    └── main
        ├── com
        │   └── zetcode
        │       └── DisplayImage.java
        └── images
            └── snake.jpg

5 directories, 3 files

With the tree command, we show the directory structure of the project.

build.xml
<?xml version="1.0"?>
<project name="DisplayImage" default="compile">
        
  <target name="init">
        <mkdir dir="build/classes"/>
  </target>

  <target name="compile" depends="init">
        <javac includeantruntime="false" srcdir="src" destdir="build/classes"/>
  </target>

  <target name="clean">        
        <delete dir="build"/>
  </target>
</project>

This is the Ant build file. We have tasks for creating directories, compiling source code, and cleaning up.

private ImageIcon loadImage() {

    ImageIcon ii = new ImageIcon("src/main/images/snake.jpg");
    return ii;
}

We use the src/main/images/snake.jpg path.

$ ant
Buildfile: /home/janbodnar/prog/javaimages/displayimageant/build.xml

init:

compile:
    [javac] Compiling 1 source file to /home/janbodnar/prog/javaimages/displayimageant/build/classes

BUILD SUCCESSFUL
Total time: 2 seconds

We build the project.

$ java -cp build/classes/ com.zetcode.DisplayImage

The application is launched.

Displaying image in NetBeans

In NetBeans, we create a Java application.

We create a new folder. We right-click on the Source Packages and select New — Folder.

Creating a folder in NetBeans
Figure: Creating a folder in NetBeans

We call the folder images. Its parent directory is src. Using a drag and drop operation, we copy the snake.jpg file to the images subdirectory.

private ImageIcon loadImage() {

    ImageIcon ii = new ImageIcon("src/images/snake.jpg");
    return ii;
}

In NetBeans, we have used the src/images/snake.jpg path.

System.out.println(System.getProperty("user.dir"));

The application's current working directory is the project directory, DisplayImageEx in our case. We can figure out the current working directory with the user.dir system property. The src directory is a subdirectory of the project directory.

Project in NetBeans
Figure: Project structure in NetBeans

The figure show the actual project structure in NetBeans.

Displaying image in Eclipse

In Eclipse, we create a Java project. We right-click on the project node and select New — Source Folder.

We call the folder name images. Unlike in NetBeans, its parent directory is the project folder. Using a drag and drop operation, we copy the snake.jpg file to the images subdirectory.

private ImageIcon loadImage() {

    ImageIcon ii = new ImageIcon("images/snake.jpg");
    return ii;
}

In Eclipse, we have used the images/snake.jpg path.

Project in Eclipse
Figure: Project structure in Eclipse

The figure show the actual project structure in Eclipse.

This was the Displaying image in Java tutorial. We have built a Swing application that displays an image using command line tools, Ant, NetBeans, and Eclipse. You might also want to check the ImageIcon tutorial, Reading and writing ICO files in Java, Java Swing tutorial, Java 2D tutorial, or Java Games tutorial.