Skip to content

🖼️ “You Won’t Believe How Easy It Is to Build This Java Image Viewer! (Only 100 Lines of Code!)”

Looking for your next mini Java project that’s fun, visual, and impressive?

In this post, you’ll learn how to build a Java Image Viewer using Swing. You’ll be able to select an image from your computer and display it inside a beautiful GUI window — all in under 100 lines of code!


🧠 What You’ll Learn

  • How to use JFileChooser to browse files
  • How to display images with ImageIcon
  • How to design a basic GUI with JFrame, JPanel, and JLabel
  • Optional navigation buttons like Next, Previous, Zoom, etc.

🔧 What You Need

  • Java 8 or later
  • Any IDE (like IntelliJ, Eclipse, or VS Code)
  • A few local image files (JPG, PNG)

🚀 Let’s Build It

🔍 Step-by-Step Preview

  1. Select an image file using a dialog
  2. Show that image in a window
  3. Boom — you’ve got your viewer!

📦 Complete Java Code

ImageViewer.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class ImageViewer extends JFrame {

    private JLabel imageLabel;
    private JButton openButton;

    public ImageViewer() {
        super("Java Image Viewer");

        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);

        openButton = new JButton("Open Image");

        openButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openImage();
            }
        });

        this.setLayout(new BorderLayout());
        this.add(openButton, BorderLayout.NORTH);
        this.add(new JScrollPane(imageLabel), BorderLayout.CENTER);

        this.setSize(800, 600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null); // Center on screen
        this.setVisible(true);
    }

    private void openImage() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Select an Image");
        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            ImageIcon icon = new ImageIcon(selectedFile.getAbsolutePath());

            // Resize image if it's too large
            Image scaledImage = icon.getImage().getScaledInstance(
                    imageLabel.getWidth(), imageLabel.getHeight(), Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(scaledImage));
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ImageViewer());
    }
}

🔍 Line-by-Line Breakdown

🏗️ GUI Construction

public class ImageViewer extends JFrame {

We create a custom class ImageViewer that extends JFrame — the main application window.

imageLabel = new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);

A JLabel is used to hold and display the image. We center it for better viewing.

openButton = new JButton("Open Image");

A button that lets users pick an image from their computer.

🎯 Button Action

openButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        openImage();
    }
});

When the button is clicked, the openImage() method is called to trigger the file picker and load the image.

📁 File Chooser and Image Loading

JFileChooser fileChooser = new JFileChooser();

Creates a dialog to let the user select an image file.

File selectedFile = fileChooser.getSelectedFile();
ImageIcon icon = new ImageIcon(selectedFile.getAbsolutePath());

Loads the selected file as an ImageIcon.


🖼️ Resizing the Image

Image scaledImage = icon.getImage().getScaledInstance(
    imageLabel.getWidth(), imageLabel.getHeight(), Image.SCALE_SMOOTH);

Ensures the image fits within the viewer window using smooth scaling.
imageLabel.setIcon(new ImageIcon(scaledImage));

Finally, the scaled image is displayed in the JLabel.

🧱 Window Setup

this.setLayout(new BorderLayout());

Sets the layout of the JFrame.

this.add(openButton, BorderLayout.NORTH);
this.add(new JScrollPane(imageLabel), BorderLayout.CENTER);

Places the button at the top and the image in the center inside a scroll pane (in case it overflows).


🔁 Main Method

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new ImageViewer());
}

Launches the GUI in the Swing thread to avoid UI glitches.


🧠 Extra Challenges for Readers

Want to make it even cooler?

  • Add Next/Previous buttons to browse multiple images in a folder
  • Add Zoom in/out functionality
  • Add Drag & Drop image support
  • Add dark/light mode toggle with UIManager.setLookAndFeel

✅ Final Output

🎉 Wrapping Up

You just built a fully functional Java Image Viewer from scratch using Swing! This project teaches you file handling, GUI design, event listeners, and even a touch of image scaling.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *