How do I scale and paint an image in Swing?

Java Image Tutorials

In the previous post, we chose file formats and exported images. In this example, we will display one image at different sizes, keep its aspect ratio, and compare three interpolation methods. Use JDK 25. The program creates a small sample image, so no input file is required.

Paint inside a component

For custom Swing drawing, extend JPanel and override paintComponent(Graphics). Call super.paintComponent(g) first so the panel can paint its background. Then use a copy of the graphics context and dispose of that copy when finished. Keep the graphics context supplied by Swing intact.

Swing calls the painting method when the component needs updating, including after resizing. When your application changes something that affects its appearance, call repaint() to request another paint. Avoid loading files or performing expensive calculations inside the painting method.

Keep the aspect ratio

Suppose an image is 160 × 100 pixels. Its aspect ratio is 1.6. Stretching it to 300 × 300 would distort the image. To fit it inside an available area, calculate one scale factor for both dimensions:

scale = min(availableWidth / imageWidth, availableHeight / imageHeight)
drawWidth = imageWidth * scale
drawHeight = imageHeight * scale

Use floating-point division. Center the result by dividing the remaining space by two. This leaves empty space above and below, or on the left and right. Integer rounding can introduce a small ratio difference of less than a pixel in a dimension.

Choose interpolation

Interpolation determines how Java 2D samples pixels when drawing at a different size.

Hint value What to look for
VALUE_INTERPOLATION_NEAREST_NEIGHBOR Sharp blocks when enlarged; useful for pixel art
VALUE_INTERPOLATION_BILINEAR Smoother transitions; a useful starting point for general images
VALUE_INTERPOLATION_BICUBIC Uses a larger neighborhood; can produce smoother detail but may cost more work

Set these values with RenderingHints.KEY_INTERPOLATION. They are rendering hints; results can vary with the graphics implementation and destination. Shape antialiasing and image interpolation are separate settings. Enabling antialiasing alone does not select the image scaling algorithm.

Complete Java example

Save this file as ScaleImageExample.java.

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ScaleImageExample {
    private static final String[] NAMES = {"Nearest neighbor", "Bilinear", "Bicubic"};
    private static final Object[] HINTS = {
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC
    };

    public static void main(String[] args) throws Exception {
        BufferedImage image = createImage();
        if (args.length == 1 && args[0].equals("--export")) {
            SwingUtilities.invokeAndWait(() -> {
                try {
                    exportPanels(image);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            return;
        }
        if (GraphicsEnvironment.isHeadless()) {
            System.out.println("No display available. Run with --export instead.");
            return;
        }
        SwingUtilities.invokeLater(() -> showWindow(image));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(160, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(8, 8, 144, 84);
            g.setColor(Color.ORANGE);
            g.fillOval(20, 20, 50, 50);
            g.setColor(Color.WHITE);
            g.drawLine(0, 99, 159, 0);
            g.drawString("Java", 90, 60);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static void showWindow(BufferedImage image) {
        JPanel content = new JPanel(new GridLayout(1, 3, 8, 8));
        for (int i = 0; i < HINTS.length; i++) {
            content.add(new ImagePanel(image, NAMES[i], HINTS[i]));
        }
        JFrame frame = new JFrame("Java image scaling");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void exportPanels(BufferedImage image) throws IOException {
        for (int i = 0; i < HINTS.length; i++) {
            ImagePanel panel = new ImagePanel(image, NAMES[i], HINTS[i]);
            panel.setSize(320, 260);
            BufferedImage output = new BufferedImage(320, 260, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = output.createGraphics();
            try {
                panel.paint(g);
            } finally {
                g.dispose();
            }
            File file = new File("scaled-" + i + ".png");
            if (!ImageIO.write(output, "png", file)) {
                throw new IOException("No PNG writer available");
            }
            System.out.println("Saved " + file.getName() + " (320 x 260)");
        }
    }

    private static class ImagePanel extends JPanel {
        private final BufferedImage image;
        private final Object interpolation;

        ImagePanel(BufferedImage image, String title, Object interpolation) {
            this.image = image;
            this.interpolation = interpolation;
            setOpaque(true);
            setBackground(new Color(235, 235, 235));
            setBorder(BorderFactory.createTitledBorder(title));
            setPreferredSize(new Dimension(320, 260));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Insets insets = getInsets();
            int availableWidth = getWidth() - insets.left - insets.right;
            int availableHeight = getHeight() - insets.top - insets.bottom;
            if (availableWidth <= 0 || availableHeight <= 0) {
                return;
            }
            double scale = Math.min(
                    (double) availableWidth / image.getWidth(),
                    (double) availableHeight / image.getHeight());
            int width = Math.max(1, (int) Math.round(image.getWidth() * scale));
            int height = Math.max(1, (int) Math.round(image.getHeight() * scale));
            int x = insets.left + (availableWidth - width) / 2;
            int y = insets.top + (availableHeight - height) / 2;

            Graphics2D copy = (Graphics2D) g.create();
            try {
                copy.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation);
                copy.drawImage(image, x, y, width, height, this);
            } finally {
                copy.dispose();
            }
        }
    }
}

Run the program

Compile and launch on a desktop:

javac --release 25 ScaleImageExample.java
java ScaleImageExample

Scale Image Example

A window titled Java image scaling should contain three labeled panels. Each shows a blue rectangle, orange circle, diagonal line, and text. Resize the window horizontally and vertically. Each image should remain centered and retain its shape. The panel background shows through transparent parts of the source image.

You can also render the panels to PNG files without a display:

java -Djava.awt.headless=true ScaleImageExample --export

Expected console output:

Saved scaled-0.png (320 x 260)
Saved scaled-1.png (320 x 260)
Saved scaled-2.png (320 x 260)

The files are written to the working directory and replaced on later export runs. Open them side by side and zoom in on the diagonal line and circle. File 0 uses nearest neighbor, file 1 uses bilinear interpolation, and file 2 uses bicubic interpolation. Exact font appearance and border dimensions depend on the environment.

How the drawing works

The drawImage(image, x, y, width, height, observer) overload scales the source into the destination rectangle. The original BufferedImage stays 160 × 100 pixels. Display scaling does not resize its stored pixel grid or modify a file.

The panel subtracts its border insets before calculating the available area. This keeps the drawing inside the titled border. Transparent source pixels reveal the panel background, which super.paintComponent(g) paints first.

Passing this supplies the panel as an ImageObserver. A BufferedImage already has its pixel data, so this example does not need to wait for asynchronous image loading.

We create the source before scheduling the UI. Swing component construction and updates happen on the Event Dispatch Thread. The export mode uses that thread too. Its call to panel.paint(g) deliberately renders the complete component, including its border, into an offscreen image. In a normal interactive application, request screen painting with repaint() instead of calling paint() yourself.

For an external file, load it with ImageIO.read() before constructing the UI and check for a null result, as in Week 01. An interactive Open action should use a background worker for file I/O so the UI stays responsive.

This example scales from the original image on every paint. For large images, caching a scaled copy can help, but rebuild the cache when its target size or interpolation changes. Always scale from the original rather than repeatedly resizing a previously resized image. Strong downscaling may need more careful resampling than a single interpolation pass.

Try it yourself

Prevent enlargement by replacing the scale calculation with:

double scale = Math.min(1.0, Math.min(
        (double) availableWidth / image.getWidth(),
        (double) availableHeight / image.getHeight()));

Make the window larger. The image should stay at its original logical drawing size and remain centered. Make it smaller, and the image should shrink to fit. On a display with scaling enabled, logical drawing units do not necessarily correspond one-to-one with physical screen pixels.

Next, load a photograph and compare the interpolation methods when shrinking it. Which setting gives the most useful result for your image?

In the next post, we will use double buffering and animate an object with a Swing timer.

References

How do I arrange components using BorderLayout in Java Swing?

Use BorderLayout to arrange components around a central area. It works well for a window with a header at the top, a status bar at the bottom, and content in the middle.

In this example, you will place a button in each of the five regions and see how they resize with the window.

Source code

Save the following code as BorderLayoutExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BorderLayoutExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JPanel panel = new JPanel(new BorderLayout(8, 8));
        panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));

        panel.add(new JButton("North"), BorderLayout.NORTH);
        panel.add(new JButton("South"), BorderLayout.SOUTH);
        panel.add(new JButton("West"), BorderLayout.WEST);
        panel.add(new JButton("East"), BorderLayout.EAST);
        panel.add(new JButton("Center"), BorderLayout.CENTER);

        JFrame frame = new JFrame("BorderLayout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.setSize(480, 260);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the five BorderLayout regions, with North and South spanning the width and Center between West and East

Explanation

new BorderLayout(8, 8) sets an 8-pixel horizontal gap and an 8-pixel vertical gap between neighboring components. The empty border adds 12 pixels of padding around the panel.

The second argument to panel.add() selects the region:

panel.add(new JButton("Center"), BorderLayout.CENTER);

Each region uses the available space differently:

Region How it behaves when the window grows
NORTH and SOUTH Stretch horizontally and keep their preferred height
WEST and EAST Stretch vertically between the top and bottom regions and keep their preferred width
CENTER Fills the space left over in both directions

Each region holds one component. To place several controls in the same region, put them in a JPanel and add that panel to the region. For example, a header panel might contain a title and several buttons.

Run the example

javac BorderLayoutExample.java
java BorderLayoutExample

Drag the right edge of the window outward. The North, Center, and South buttons grow wider, while West and East keep their widths. Then drag the bottom edge downward: West, Center, and East grow taller.

How do I map a Java class to a database table?

Hibernate ORM Tutorial Series

Previous article gave us a runnable Maven project that saves and loads a Book. In this article, we will expand that same entity with an ISBN and publication date, give its columns explicit names, and inspect the resulting table. We will continue using Jakarta Persistence and an in-memory H2 database. Author and Publisher will become entities when we reach relationships in later tutorial.

Understand the mapping

An entity represents data with an identity. Its identifier connects a Java object to a database row. Basic attributes such as strings and dates become columns in that row.

Here is the mapping we will implement:

Java element Database element Purpose
Book books Catalog table
id (Long) id (bigint) Assigned primary key
title (String) title (varchar(200)) Required title
isbn (String) isbn (varchar(13)) Required unique ISBN-13
publicationDate (LocalDate) publication_date (date) Optional date

ISBN is a string because it is an identifier rather than a quantity. Our sample stores the 13 digits without hyphens. Column length describes storage; it does not validate an ISBN checksum or require exactly 13 characters.

1. Keep the existing project configuration

Continue in hibernate-book-catalog from previous tutorial using JDK 25 and Maven 3.9 or later. Keep its complete pom.xml, including compiler plugin 3.14.1, execution plugin 3.6.3, and main class org.kodejava.hibernate.BookCatalogApp.

All file paths below are relative to the Maven project root. Replace both Java files in full. We include the persistence configuration again so the example’s database settings are explicit.

2. Expand the Book entity

File: src/main/java/org/kodejava/hibernate/Book.java

package org.kodejava.hibernate;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;

@Entity
@Table(name = "books")
public class Book {
    @Id
    private Long id;

    @Column(name = "title", nullable = false, length = 200)
    private String title;

    @Column(name = "isbn", nullable = false, unique = true, length = 13)
    private String isbn;

    @Column(name = "publication_date")
    private LocalDate publicationDate;

    protected Book() {
    }

    public Book(Long id, String title, String isbn, LocalDate publicationDate) {
        this.id = id;
        this.title = title;
        this.isbn = isbn;
        this.publicationDate = publicationDate;
    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getIsbn() {
        return isbn;
    }

    public LocalDate getPublicationDate() {
        return publicationDate;
    }
}

@Entity makes the class part of the persistence model. @Table chooses its SQL table name. The entity name remains Book; SQL table names and entity names are separate concepts.

@Id identifies the primary key. It remains manually assigned so that we can focus on mapping. Later tutorial introduces generated identifiers.

@Column controls the column name and schema details. In our generated schema, nullable = false produces a non-null constraint, length sets string capacity, and unique = true requests a single-column unique constraint. See the official Column API.

publicationDate uses LocalDate, which Hibernate maps to SQL date; it has no time of day or time zone. No @Temporal annotation is needed. Nullability defaults to true, so this attribute can be absent. The explicit column name avoids relying on an automatic camel-case-to-underscore conversion.

Why are the annotations on fields?

The placement of @Id selects field access for this entity. Hibernate reads and writes fields directly, including private fields, so setters are unnecessary here. Keep mapping annotations on fields consistently. Property access instead places mappings on getters; do not mix the approaches accidentally.

Supported basic fields are persistent by default, even without @Column. To exclude a field, use Jakarta Persistence @Transient, for example for an in-memory UI selection flag. Adding a getter alone does not add a column when using field access. The Hibernate domain model guide explains these access strategies.

The entity is non-final and has a protected no-argument constructor. Hibernate needs to instantiate it when reading rows. Our public constructor is the convenient application-facing way to create a new book.

3. Configure H2 and schema generation

File: src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
             version="3.2">
    <persistence-unit name="book-catalog" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>org.kodejava.hibernate.Book</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:book_catalog"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

The configuration is unchanged from previous tutorial. drop-and-create rebuilds the disposable schema at startup, so the new columns appear without a manual ALTER TABLE. It deletes existing mapped tables and data; use this setting only for our in-memory example. Mapping changes do not automatically migrate an existing production database. Later tutorial will introduce migrations.

4. Persist and reload the expanded entity

File: src/main/java/org/kodejava/hibernate/BookCatalogApp.java

package org.kodejava.hibernate;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import java.time.LocalDate;

public class BookCatalogApp {
    public static void main(String[] args) {
        try (EntityManagerFactory factory =
                     Persistence.createEntityManagerFactory("book-catalog")) {
            saveBook(factory);
            loadBook(factory);
        }
    }

    private static void saveBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                Book book = new Book(1L, "Effective Java", "9780134685991",
                        LocalDate.of(2018, 1, 6));
                entityManager.persist(book);
                transaction.commit();
                System.out.println("Saved book: " + book.getTitle());
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }

    private static void loadBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            Book book = entityManager.find(Book.class, 1L);
            if (book == null) {
                throw new IllegalStateException("Book 1 was not found");
            }
            System.out.println("ID: " + book.getId());
            System.out.println("Title: " + book.getTitle());
            System.out.println("ISBN: " + book.getIsbn());
            System.out.println("Publication date: " + book.getPublicationDate());
        }
    }
}

The publication date used here is an example value for demonstrating date mapping, not the book’s verified publication date. The write transaction commits the new row. Loading through a new entity manager then reconstructs a Book from stored values, rather than returning the object from the original persistence context. Resource handling and transaction boundaries follow previous tutorial.

5. Run and inspect the result

From the directory containing pom.xml, run:

mvn clean compile exec:java

Expected application output, interleaved with Hibernate logs:

Saved book: Effective Java
ID: 1
Title: Effective Java
ISBN: 9780134685991
Publication date: 2018-01-06

The generated table definition should be equivalent to:

create table books (
    id bigint not null,
    title varchar(200) not null,
    isbn varchar(13) not null unique,
    publication_date date,
    primary key (id)
)

Column order and generated constraint names may differ. Look for the column types, the primary key, and the unique ISBN constraint rather than matching the SQL text exactly. Hibernate also prints an insert and a select with JDBC bind placeholders.

Mapping constraints and input validation

A non-null column does not reject an empty title such as "". A string length limit does not validate ISBN digits. Add application validation when collecting catalog input. The database constraints still protect stored data, including writes made outside Hibernate.

To explore the mapping, change the sample date to null and rerun: the final line becomes Publication date: null. To see the unique constraint, persist a second Book with another ID but the same ISBN inside the write transaction. The commit should fail; the exact exception and database message can vary. Restore the working sample before continuing.

On next tutorial, we will replace manually assigned IDs with generated entity identifiers while keeping this Book mapping.

Maven Dependencies

Keep these dependencies in pom.xml. Hibernate Core brings in the Jakarta Persistence API transitively. Java’s LocalDate needs no extra library. H2 is required at runtime because our Java code uses the Jakarta Persistence API rather than H2-specific classes.

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>7.4.17.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.5.252</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

How do I split a string and keep its delimiters in Java 21?

Sometimes you need both the pieces of a string and the separators between them. For example, a text-processing tool might need to preserve commas and semicolons while inspecting individual values.

Java 21 provides String.splitWithDelimiters() for this task.

1. Choose the separators

Our input is:

red,green;blue;

The regular expression [,;] matches either a comma or a semicolon.

Unlike split(), splitWithDelimiters() includes matched separators as elements in the returned array. See the Java 21 String API.

2. Keep the pieces and reconstruct the text

Save the following as KeepDelimitersExample.java:

import java.util.Arrays;

public class KeepDelimitersExample {
    public static void main(String[] args) {
        String text = "red,green;blue;";
        String regex = "[,;]";

        System.out.println(
                "split: " + Arrays.toString(text.split(regex, -1)));

        String[] parts = text.splitWithDelimiters(regex, -1);
        System.out.println("keep: " + Arrays.toString(parts));

        System.out.println("Rebuilt: " + String.join("", parts));

        System.out.println("limit 2: " + Arrays.toString(
                text.splitWithDelimiters(regex, 2)));

        System.out.println("limit 0: " + Arrays.toString(
                text.splitWithDelimiters(regex, 0)));
    }
}

The program compares ordinary splitting with delimiter-preserving splitting. It then joins the preserved pieces without adding any extra characters.

3. Compile and run

From the directory containing the file:

javac --release 21 KeepDelimitersExample.java
java KeepDelimitersExample

Output:

split: [red, green, blue, ]
keep: [red, ,, green, ;, blue, ;, ]
Rebuilt: red,green;blue;
limit 2: [red, ,, green;blue;]
limit 0: [red, ,, green, ;, blue, ;]

The two adjacent commas in the keep line can look confusing: one is a delimiter element, while the other is punctuation added by Arrays.toString().

4. Understand the limit

The second argument controls splitting:

Limit Behavior
Negative Processes all matches and preserves trailing empty strings.
Zero Processes all matches but removes trailing empty strings.
Positive Processes at most limit - 1 matches, leaving the remaining input together.

With limit 2, only the first comma is processed. The result therefore contains three elements: "red", ",", and "green;blue;".

A positive limit does not directly cap the array length at that number, because delimiter elements are included. These rules are specified in the method documentation.

Best practices

  • Use this method when separators carry information you need later.
  • Test leading, consecutive, and trailing separators with your chosen pattern.
  • Remember that the first argument is a regular expression. Use Pattern.quote() when a user-supplied separator should be treated literally.
  • Use a CSV parser for quoted CSV fields; splitting on commas alone does not implement CSV rules.

Summary

splitWithDelimiters() lets you inspect string segments while preserving their separators. Choose the limit deliberately, especially when trailing empty values matter.

How do I display a message dialog in Java Swing?

Use JOptionPane.showMessageDialog() to display a short message with an OK button. This example opens an information dialog without creating a separate JFrame.

Source code

Save the following code as MessageDialogExample.java:

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class MessageDialogExample {
    void main() {
        SwingUtilities.invokeLater(this::showMessage);
    }

    private void showMessage() {
        JOptionPane.showMessageDialog(
                null,
                "Hello from Swing!",
                "Message",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

What the dialog looks like

Illustration of a dialog titled Message, with the text Hello from Swing! and an OK button

The icon and window styling depend on your system and Swing look and feel.

Explanation

The showMessageDialog() call uses four arguments:

Argument Purpose
null Shows the dialog without positioning it relative to an existing component
"Hello from Swing!" Sets the message shown inside the dialog
"Message" Sets the title shown in the title bar
JOptionPane.INFORMATION_MESSAGE Selects the information message type, which usually displays an information icon

If your application already has a window, pass its JFrame instead of null so Swing can position the dialog relative to that window.

SwingUtilities.invokeLater() schedules showMessage() on Swing’s event dispatch thread. The dialog is modal, so the call to showMessageDialog() returns after the user dismisses the dialog. It returns no value. If you need to ask a question and read the user’s choice, use showConfirmDialog().

Run the example

javac MessageDialogExample.java
java MessageDialogExample

A dialog titled Message displays Hello from Swing!. Click OK to dismiss it.