How do I create, load, and display an image in Java?

In this example, you will draw a blue card in memory, save it as a PNG file, open that file, and show the loaded image in a Swing window. The program creates its own image.

What is a pixel?

A raster image is a grid of pixels. In a BufferedImage, the top-left pixel is at (0, 0). The x coordinate increases to the right, and the y coordinate increases downward.

This example uses BufferedImage.TYPE_INT_ARGB. Each pixel has four values for alpha, red, green, and blue. Alpha controls opacity. A value of 0 means fully transparent, and 255 means fully opaque. The program draws inside the image and leaves a transparent border, which PNG preserves when you save the file.

Java example

Save the following code as JavaImageBasics.java.

package org.kodejava.awt.image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class JavaImageBasics {
    public static void main(String[] args) throws IOException {
        BufferedImage image = createImage();

        File file = new File("java-image.png");
        if (!ImageIO.write(image, "png", file)) {
            throw new IOException("PNG writer is unavailable");
        }

        BufferedImage loadedImage = ImageIO.read(file);
        if (loadedImage == null) {
            throw new IOException("Unrecognized image format: " + file);
        }

        System.out.printf("%s: %d x %d pixels%n",
                file.getName(), loadedImage.getWidth(), loadedImage.getHeight());

        if (!GraphicsEnvironment.isHeadless()) {
            SwingUtilities.invokeLater(() -> showImage(loadedImage));
        }
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics = image.createGraphics();
        try {
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setColor(new Color(33, 99, 200));
            graphics.fillRoundRect(20, 20, 280, 160, 30, 30);
            graphics.setColor(Color.WHITE);
            graphics.drawString("Hello, Java Images!", 100, 105);
        } finally {
            graphics.dispose();
        }

        return image;
    }

    private static void showImage(BufferedImage image) {
        JFrame frame = new JFrame("Java Images");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel(new ImageIcon(image)));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Run the program

Open a terminal in the folder containing the Java file and run these commands.

javac JavaImageBasics.java
java JavaImageBasics

The program writes java-image.png to the working directory and prints the dimensions of the loaded file.

Java Image

java-image.png: 320 x 200 pixels

On a desktop, a Swing window shows the blue card. The transparent border lets the component background show through. In a headless environment, the program still writes and reads the file and prints its dimensions.

How it works

  1. Create. createGraphics() returns a Graphics2D object that draws directly into the BufferedImage. The finally block calls dispose() to release the drawing context.
  2. Save. ImageIO.write() selects an encoder using the format name "png". It returns false if no suitable writer is available.
  3. Load. ImageIO.read() decodes the file into a new BufferedImage. It returns null if no installed reader recognizes the data. An error while opening or reading the file can throw an IOException.
  4. Display. ImageIcon wraps the loaded image, and JLabel displays the icon. SwingUtilities.invokeLater() creates the window on Swing’s Event Dispatch Thread after the file has been read.

Try it yourself

Change the image size to 480 × 240 pixels. Resize the blue rectangle so it still has a 20-pixel margin on all sides. Then print the alpha value for the top-left pixel and for a pixel inside the blue rectangle.

int cornerAlpha = loadedImage.getRGB(0, 0) >>> 24;
int cardAlpha = loadedImage.getRGB(30, 50) >>> 24;
System.out.printf("Corner alpha = %d, card alpha = %d%n",
        cornerAlpha, cardAlpha);

Add this snippet after the null check in main(). The expected values are 0 for the transparent corner and 255 for the solid blue area.

Maven dependencies

AWT, Swing, and Image I/O are part of the JDK’s java.desktop module. This example needs no extra Maven dependencies. If you use a modular project, add requires java.desktop; to your module declaration.

References

Next week — How do I choose an image file format in Java?

How do I get the first and last elements of a List in Java?

You can use getFirst() and getLast() to read the first and last elements of a list without calculating their indexes.

In this example, you will read the first and last programming language names from a list.

Source code

Save the following code as FirstLastListExample.java:

import java.util.List;

public class FirstLastListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        if (languages.isEmpty()) {
            IO.println("The list is empty.");
            return;
        }

        String firstLanguage = languages.getFirst();
        String lastLanguage = languages.getLast();

        IO.println("Languages: " + languages);
        IO.println("First language: " + firstLanguage);
        IO.println("Last language: " + lastLanguage);
    }
}

Explanation

The example creates a list containing three strings:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

A List maintains its elements in a defined order. Here, "Java" is the first element and "Kotlin" is the last.

Checking for an empty list

Before reading either element, the program checks whether the list is empty:

if (languages.isEmpty()) {
    IO.println("The list is empty.");
    return;
}

Both getFirst() and getLast() throw a NoSuchElementException when called on an empty list.

The return statement ends the method before either call can happen.

Reading the first element

Use getFirst() to retrieve the element at the beginning:

String firstLanguage = languages.getFirst();

For a nonempty list, this returns the same element as get(0).

Reading the last element

Use getLast() to retrieve the element at the end:

String lastLanguage = languages.getLast();

For a nonempty list, this returns the same element as:

languages.get(languages.size() - 1)

The named methods make the intent clear without requiring index calculations. Neither method removes an element or changes the list.

Run the example

Compile and run the file:

javac FirstLastListExample.java
java FirstLastListExample

Output

Languages: [Java, Python, Kotlin]
First language: Java
Last language: Kotlin

If you replace the list declaration with an empty list:

List<String> languages = List.of();

The output becomes:

The list is empty.

For a list containing only one element, getFirst() and getLast() return that same element.

How do I keep a recent files list with SequencedMap in Java 21?

A recent files menu should move a reopened file to the top instead of showing it twice. Once the menu is full, opening a new file should remove the oldest entry. In Java 21, a LinkedHashMap can do both through the SequencedMap interface. See the Java 21 SequencedMap API.

1. Move a reopened file to the newest position

Use a LinkedHashMap to store each file name and its path. The example keeps the oldest entry first and the newest entry last.

On a default LinkedHashMap, calling put() for an existing key changes its value but leaves it in the same position. Calling putLast() also moves the entry to the end. That means reopening notes.txt makes it the newest entry without adding a duplicate. See the Java 21 LinkedHashMap API.

2. Remove the oldest entry when the list is full

After recording a file, check the map’s size. If it exceeds the limit, call pollFirstEntry() to remove and return the oldest entry. Use reversed() when displaying the menu so the newest entry appears first.

3. Run the complete example

Save this code as RecentFilesExample.java. The paths are sample strings; the program does not open any files.

import java.util.LinkedHashMap;
import java.util.SequencedMap;

public class RecentFilesExample {
    private static final int LIMIT = 3;

    public static void main(String[] args) {
        SequencedMap<String, String> recent = new LinkedHashMap<>();

        remember(recent, "notes.txt", "/work/notes.txt");
        remember(recent, "plan.txt", "/work/plan.txt");
        remember(recent, "ideas.txt", "/work/ideas.txt");
        remember(recent, "notes.txt", "/work/notes.txt");

        System.out.println("After reopening: " + recent.sequencedKeySet());

        var removed = remember(recent, "draft.txt", "/work/draft.txt");
        System.out.println("Removed: " + removed);
        System.out.println("Newest first: " + recent.reversed().sequencedKeySet());
    }

    private static String remember(SequencedMap<String, String> recent,
                                   String name, String path) {
        recent.putLast(name, path);
        if (recent.size() > LIMIT) {
            return recent.pollFirstEntry().getKey();
        }
        return null;
    }
}

Compile and run it from the directory containing the file:

javac --release 21 RecentFilesExample.java
java RecentFilesExample

Output:

After reopening: [plan.txt, ideas.txt, notes.txt]
Removed: plan.txt
Newest first: [draft.txt, notes.txt, ideas.txt]

Reopening notes.txt makes plan.txt the oldest entry. Adding draft.txt takes the map over its three-file limit, so plan.txt is removed.

Best practices

  • Use a full path or another stable identifier as the key in a real app. Two folders can contain files with the same name.
  • Update the list after a file opens successfully so failed attempts do not appear in the menu.
  • Treat reversed() as a live view. If you need a list that stays the same when the map changes, take a snapshot with List.copyOf(recent.reversed().sequencedKeySet()).

How do I loop through the entries of a HashMap in Java?

You can use entrySet() with an enhanced for loop to read each key-value pair in a HashMap.

In this example, you will store product names and their quantities, then print each entry.

Source code

Save the following code as HashMapLoopExample.java:

import java.util.HashMap;
import java.util.Map;

public class HashMapLoopExample {
    void main() {
        Map<String, Integer> inventory = new HashMap<>();

        inventory.put("Notebook", 12);
        inventory.put("Pen", 30);
        inventory.put("Pencil", 20);

        for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
            String product = entry.getKey();
            int quantity = entry.getValue();

            IO.println(product + ": " + quantity);
        }

        IO.println("Total products: " + inventory.size());
    }
}

Explanation

A map stores values associated with unique keys. In this example, each product name is a key, and its quantity is the corresponding value:

Map<String, Integer> inventory = new HashMap<>();

The type arguments specify that keys are strings and values are integers. Java generics use reference types, so the value type is Integer rather than int.

Adding entries

Use put() to add a key-value pair:

inventory.put("Notebook", 12);

Java automatically boxes the quantity into an Integer.

If you call put() again with an existing key, the new value replaces the previous value for that key.

Reading entries with entrySet()

The entrySet() method provides a set view of the map’s entries:

inventory.entrySet()

Each entry contains both a key and its associated value. The enhanced for loop reads one entry at a time:

for (Map.Entry<String, Integer> entry : inventory.entrySet()) {

Inside the loop, use getKey() and getValue() to access the pair:

String product = entry.getKey();
int quantity = entry.getValue();

Assigning the Integer value to an int automatically unboxes it. All values in this example are non-null.

Using entrySet() lets you read the key and value together without performing a separate lookup with get().

Counting entries

The size() method returns the number of key-value pairs:

inventory.size()

Here, the result is 3. It counts product entries, not the sum of their quantities.

Run the example

Compile and run the file:

javac HashMapLoopExample.java
java HashMapLoopExample

Example output

Notebook: 12
Pen: 30
Pencil: 20
Total products: 3

A HashMap does not guarantee iteration order, so the product lines may appear in a different order.

Using forEach()

For a shorter alternative, replace the loop with:

inventory.forEach((product, quantity) ->
        IO.println(product + ": " + quantity));

This passes each key and value to the lambda expression. It also follows the map’s iteration order, which remains unspecified for a HashMap.

How do I animate a falling domino spiral in Java Swing?

A domino chain reaction can be animated by giving each tile a slightly later start time. In this SwingLoops example, 92 dominoes are placed on a spiral. Each one appears to fall toward the next, changing from blue to orange as it moves. You can create the effect using Java Swing and Java 2D without a physics engine or external libraries.

Domino Spiral

Domino Spiral

Source code

Save this example as DominoSpiral.java.

package org.kodejava.swing.animation;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;

public class DominoSpiral extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int COUNT = 92;
    private static final double START = 1.0;
    private static final double DELAY = 0.065;
    private static final double FALL = 0.24;
    private static final double CYCLE = 10.0;
    private static final Color BACKGROUND = new Color(10, 17, 31);

    private final double[] x = new double[COUNT];
    private final double[] y = new double[COUNT];
    private final double[] direction = new double[COUNT];
    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;

    public DominoSpiral() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(BACKGROUND);

        // Place the tiles about 13 pixels apart along the spiral.
        double angle = 0;
        double pitch = 8.5;
        for (int i = 0; i < COUNT; i++) {
            double radius = 195 - pitch * angle;
            x[i] = WIDTH / 2.0 + radius * Math.cos(angle);
            y[i] = HEIGHT / 2.0 + radius * Math.sin(angle);
            angle += 13 / Math.hypot(radius, pitch);
        }

        for (int i = 0; i < COUNT - 1; i++) {
            direction[i] = Math.atan2(y[i + 1] - y[i], x[i + 1] - x[i]);
        }
        direction[COUNT - 1] = direction[COUNT - 2];
    }

    @Override
    public void addNotify() {
        super.addNotify();
        startedAt = System.nanoTime();
        timer.start();
    }

    @Override
    public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    private static double clamp(double value) {
        return Math.max(0, Math.min(1, value));
    }

    private static Color tileColor(double progress) {
        return new Color(
                57 + (int) (193 * progress),
                171 - (int) (54 * progress),
                248 - (int) (179 * progress));
    }

    private static void drawTile(Graphics2D g, double progress) {
        double lean = 10 * progress;
        double height = 20 - 14 * progress;

        g.setColor(new Color(2, 6, 13, 150));
        g.fillOval(-5, -6, 19, 12);

        Path2D face = new Path2D.Double();
        face.moveTo(0, -4);
        face.lineTo(0, 4);
        face.lineTo(lean + 5, 4 - height);
        face.lineTo(lean + 5, -4 - height);
        face.closePath();

        g.setColor(tileColor(progress));
        g.fill(face);
        g.setColor(new Color(255, 255, 255, 155));
        g.draw(face);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

        double elapsed = (System.nanoTime() - startedAt) / 1e9;
        double t = elapsed % CYCLE;
        double fade = t < 9 ? 1 : 1 - clamp(t - 9);
        Graphics2D g = (Graphics2D) graphics.create();
        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            double scale = Math.min(getWidth() / (double) WIDTH,
                    getHeight() / (double) HEIGHT);
            g.translate((getWidth() - WIDTH * scale) / 2,
                    (getHeight() - HEIGHT * scale) / 2);
            g.scale(scale, scale);
            g.setComposite(java.awt.AlphaComposite.SrcOver.derive((float) fade));

            g.setColor(new Color(31, 49, 72));
            Path2D track = new Path2D.Double();
            track.moveTo(x[0], y[0]);
            for (int i = 1; i < COUNT; i++) {
                track.lineTo(x[i], y[i]);
            }
            g.draw(track);

            for (int i = 0; i < COUNT; i++) {
                double u = clamp((t - START - i * DELAY) / FALL);
                double progress = u * u * (3 - 2 * u);
                Graphics2D tile = (Graphics2D) g.create();
                try {
                    tile.translate(x[i], y[i]);
                    tile.rotate(direction[i]);
                    drawTile(tile, progress);
                } finally {
                    tile.dispose();
                }
            }
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Domino Spiral");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new DominoSpiral());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

Open a terminal in the directory containing the file. With a JDK installed and a desktop environment available, run:

javac DominoSpiral.java
java DominoSpiral

The window opens with a preferred drawing area of 450 × 800 pixels. Resize it to fit your screen; the drawing keeps its proportions. Close the window to exit.

Place the tiles along a spiral

The code starts with a radius of 195 pixels and reduces it by 8.5 pixels for each radian of angular travel. Sine and cosine convert the radius and angle to a position on the screen.

Using the same angle increment everywhere would spread out the outer tiles and crowd the inner ones. Instead, the code uses this approximation:

angle += 13 / Math.hypot(radius, pitch);

For a small angle change, the distance traveled along this spiral is approximately the angle change multiplied by sqrt(radius² + pitch²). Dividing the desired spacing of 13 pixels by that factor gives an angle step that grows as the spiral tightens. The result is approximately even spacing. After placing the tiles, Math.atan2() determines which direction each tile should face by looking at the next tile.

Turn a delay into a chain reaction

The first tile starts one second into the cycle. Each later tile waits an additional 65 milliseconds:

double u = clamp((t - START - i * DELAY) / FALL);

A value of zero means the tile is upright, and one means it has finished falling. The fall takes 240 milliseconds, so several neighboring tiles are in motion at once. Smoothstep, u * u * (3 - 2 * u), eases the movement at both ends.

To draw the fall, the program shifts the tile’s upper edge forward and reduces its visible height. Its color shifts toward orange at the same time. This is a stylized 2D animation: the timing creates the apparent chain reaction, and the program does not calculate contact between tiles.

Repeat the animation

A Swing timer requests repaints about every 16 milliseconds. The drawing uses elapsed time from System.nanoTime(), so a delayed repaint does not change when the next tile is supposed to fall. During the final second the spiral fades away. At the ten-second boundary, the upright tiles reappear.

Try raising DELAY from 0.065 to 0.075 to slow down the chain. If you increase it further, check that START + (COUNT - 1) * DELAY + FALL still fits before the fade begins at nine seconds.

The complete source code is free to copy and run. Find more examples in the SwingLoops repository.