How do I open a Swing window on the event dispatch thread in Java?

Use SwingUtilities.invokeLater() to create and show a Swing window on the event dispatch thread (EDT). Swing uses this thread to process events such as mouse clicks and to update the interface.

This example opens a window and prints whether the code that creates it is running on the EDT.

Source code

Save the following code as SwingEdtExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class SwingEdtExample {
    void main() {
        IO.println("main() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        IO.println("showWindow() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel("Welcome to Swing", SwingConstants.CENTER));
        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

The window looks like the one in the previous example. The console messages show which thread runs each method.

Explanation

When you launch the program, main() runs outside the EDT. It schedules the showWindow() method with this line:

SwingUtilities.invokeLater(this::showWindow);

The method reference this::showWindow supplies the task. invokeLater() puts that task on Swing’s event queue and returns without waiting. The EDT runs the task when it reaches the front of the queue.

The showWindow() method creates the frame and label, adds the label to the frame, and makes the window visible. All of those steps run on the EDT. Calling showWindow() directly from main() would run those steps on the main thread instead.

SwingUtilities.isEventDispatchThread() checks the thread that is running the current code. It returns false in main() and true in showWindow().

Run the example

javac SwingEdtExample.java
java SwingEdtExample

The console prints:

main() on the EDT: false
showWindow() on the EDT: true

Keep work on the EDT short. A slow operation, such as downloading a file, can keep Swing from responding to clicks or repainting the window. Run slow work in the background and send interface updates back to the EDT.

How do I create a window using JFrame in Java?

Use JFrame to create a Swing window with a title bar and an area for components. In this example, you will open a window with a centered welcome message.

Source code

Save the following code as JFrameExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

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

    private void showWindow() {
        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel message = new JLabel(
                "Welcome to Swing", SwingConstants.CENTER);
        frame.add(message);

        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

This illustration shows the layout. The title bar and window controls may look different on your operating system.

Explanation

new JFrame("Hello, Swing!") creates the window and sets its title. EXIT_ON_CLOSE tells Java to exit the application when you close this window.

The JLabel displays Welcome to Swing. SwingConstants.CENTER centers the text horizontally, and frame.add(message) places the label inside the window.

setSize(400, 240) sets the size of the entire window, including its border and title bar. Call setLocationRelativeTo(null) after setting the size to center the window on the screen. Finally, setVisible(true) displays it.

The main() method uses SwingUtilities.invokeLater(this::showWindow) to schedule window creation on Swing’s event dispatch thread. This is the thread Swing uses to handle events and update the interface.

Run the example

Compile and run the file:

javac JFrameExample.java
java JFrameExample

A window titled Hello, Swing! opens with the welcome message in the center. Close the window to end the program.

How do I run a task using a virtual thread in Java?

Use Thread.startVirtualThread() to create and start a virtual thread in one call. Virtual threads are useful when many tasks spend time waiting for operations such as network requests.

In this example, a task prints whether it is running on a virtual thread. The main thread waits for the task to finish before printing the final message.

Source code

Save the following code as VirtualThreadExample.java:

public class VirtualThreadExample {
    void main() throws InterruptedException {
        Thread worker = Thread.startVirtualThread(() -> {
            boolean virtual = Thread.currentThread().isVirtual();
            IO.println("Running on a virtual thread: " + virtual);
        });

        worker.join();
        IO.println("The task has finished.");
    }
}

Explanation

Thread.startVirtualThread() takes a Runnable. The lambda supplies the task, and the method returns the Thread that runs it. The thread has already been started, so you do not need to call start() separately.

Inside the task, Thread.currentThread() returns the thread executing the lambda. Calling isVirtual() on that thread returns true.

Virtual threads are daemon threads, so they do not keep the JVM running on their own. Here, worker.join() keeps the main thread waiting until the worker finishes. This also ensures that the task’s message appears before the final message. The join() method can throw InterruptedException if the main thread is interrupted while waiting.

Run the example

Compile and run the file:

javac VirtualThreadExample.java
java VirtualThreadExample

Output

Running on a virtual thread: true
The task has finished.

Virtual threads help applications handle many tasks that wait for I/O. They do not make an individual calculation run faster.

How do I create and start a thread in Java?

Use Thread.ofPlatform() to create a platform thread. Pass it a Runnable that describes the work, then call start() to run that work on the new thread.

In this example, a worker thread prints its name, and the main thread waits for it to finish.

Source code

Save the following code as ThreadExample.java:

public class ThreadExample {
    void main() throws InterruptedException {
        Runnable task = () -> {
            String threadName = Thread.currentThread().getName();
            IO.println("Task running on: " + threadName);
        };

        Thread worker = Thread.ofPlatform()
                .name("worker")
                .unstarted(task);

        IO.println("Starting the worker.");
        worker.start();
        worker.join();
        IO.println("The worker has finished.");
    }
}

Explanation

The Runnable describes what the worker should do. Here, a lambda calls Thread.currentThread() to get the thread that is executing the task, then prints its name.

Thread.ofPlatform() returns a thread builder. The name("worker") call sets the thread’s name, and unstarted(task) creates the thread without running the task yet.

The call to worker.start() schedules the task to run on the new thread. If you call task.run() directly, the task runs on the current thread instead.

Waiting for the worker

worker.join() waits until the worker finishes. This ensures that the final message appears after the task’s message. Without join(), the main thread could print its final message before the worker prints anything.

The join() method can throw InterruptedException if the main thread is interrupted while waiting. This example declares that exception in main().

Run the example

Compile and run the file:

javac ThreadExample.java
java ThreadExample

Output

Starting the worker.
Task running on: worker
The worker has finished.

A Thread can be started only once. To run the same task again on a new thread, create another Thread using the same Runnable.

How do I choose an image file format in Java?

Java Image Tutorials

In the previous post, we created a transparent image and saved it as PNG. In this example, we will choose formats for different tasks, check the available Image I/O codecs, and export a transparent drawing as PNG and JPEG. The program creates its own image, so you do not need an input file.

Choose a format for your image

A file format describes how an image is stored on disk. A BufferedImage holds decoded pixels in memory. Its type, such as TYPE_INT_ARGB, is separate from the format you use to save those pixels.

Format Compression and transparency Typical use
PNG Lossless; supports full alpha transparency Screenshots, diagrams, icons, and images with text
JPEG Usually lossy; no alpha transparency Photographs where smaller files matter
GIF Lossless compression of indexed colors; up to 256 palette entries per frame and one transparent palette index Small palette graphics and simple animations
BMP Often uncompressed; alpha support varies across variants and software Compatibility with software that specifically requires BMP
TIFF Supports several compression methods; alpha depends on the image layout and reader Scanned documents, publishing, and workflows that need multiple pages or specialized metadata

For a transparent logo, start with PNG. For a photograph, try JPEG and inspect the result. For scans, follow the requirements of the receiving application, which may request TIFF.

GIF compression does not mean an arbitrary full-color image keeps all its colors: converting to a limited palette can change them. GIF also cannot preserve smooth, partially transparent edges. TIFF is a family of capabilities; test the particular compression and image layout required by your workflow.

File size depends on image content, dimensions, and encoder settings. A flat-color diagram can be smaller as PNG than JPEG. Do not assume one format always produces the smallest file.

Check codec support

A reader decodes a file into pixels. A writer encodes pixels into a file. Java 25 supplies standard Image I/O plug-ins for PNG, JPEG, GIF, BMP, TIFF, and WBMP. Additional plug-ins can add formats.

Use ImageIO.getImageReadersByFormatName() and getImageWritersByFormatName() to check registered support. The presence of a writer does not guarantee it accepts every image layout. For example, convert an ARGB image to an opaque RGB image before writing JPEG.

Complete Java example

Save this code as ImageFormatExample.java.

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ImageFormatExample {
    public static void main(String[] args) throws IOException {
        for (String format : new String[]{"png", "jpeg", "gif", "bmp", "tiff", "webp"}) {
            boolean reader = ImageIO.getImageReadersByFormatName(format).hasNext();
            boolean writer = ImageIO.getImageWritersByFormatName(format).hasNext();
            System.out.printf("%s: reader=%s, writer=%s%n", format, reader, writer);
        }

        BufferedImage source = createImage();
        BufferedImage opaque = flatten(source, Color.WHITE);

        Path directory = Path.of("image-formats-output");
        Files.createDirectories(directory);
        saveAndInspect(source, "png", directory.resolve("card.png"));
        saveAndInspect(opaque, "jpeg", directory.resolve("card.jpg"));
        saveAndInspect(opaque, "gif", directory.resolve("card.gif"));
        saveAndInspect(opaque, "bmp", directory.resolve("card.bmp"));
        saveAndInspect(opaque, "tiff", directory.resolve("card.tiff"));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(20, 20, 280, 160);
            g.setColor(new Color(255, 120, 0, 128));
            g.fillOval(0, 60, 100, 100);
            g.setColor(Color.WHITE);
            g.drawString("Java image formats", 110, 105);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static BufferedImage flatten(BufferedImage source, Color background) {
        if (background.getAlpha() != 255) {
            throw new IllegalArgumentException("Background must be opaque");
        }
        BufferedImage result = new BufferedImage(
                source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        try {
            g.setColor(background);
            g.fillRect(0, 0, result.getWidth(), result.getHeight());
            g.drawImage(source, 0, 0, null);
        } finally {
            g.dispose();
        }
        return result;
    }

    private static void saveAndInspect(BufferedImage image, String format, Path path)
            throws IOException {
        if (!ImageIO.write(image, format, path.toFile())) {
            throw new IOException("No suitable writer for " + format);
        }
        BufferedImage loaded = ImageIO.read(path.toFile());
        if (loaded == null) {
            throw new IOException("No reader recognizes " + path);
        }
        System.out.printf("%s: %d x %d, corner alpha=%d%n",
                path.getFileName(), loaded.getWidth(), loaded.getHeight(),
                loaded.getRGB(0, 0) >>> 24);
    }
}

Run the program

Open a terminal in the folder containing the source file:

javac --release 25 ImageFormatExample.java
java -Djava.awt.headless=true ImageFormatExample

The program uses Java 2D without opening a window. It works in a headless environment. It creates the image-formats-output folder in the working directory. Running it again replaces the five output files.

With the standard Java 25 plug-ins and no additional codecs, the expected console output is:

png: reader=true, writer=true
jpeg: reader=true, writer=true
gif: reader=true, writer=true
bmp: reader=true, writer=true
tiff: reader=true, writer=true
webp: reader=false, writer=false
card.png: 320 x 200, corner alpha=0
card.jpg: 320 x 200, corner alpha=255
card.gif: 320 x 200, corner alpha=255
card.bmp: 320 x 200, corner alpha=255
card.tiff: 320 x 200, corner alpha=255

Installed plug-ins can change the codec availability lines. Open the files in an image viewer: PNG keeps a transparent border, while the other exports have a white background. The orange circle is partially transparent in PNG and blended with the background in the other files. JPEG may show artifacts around text and sharp edges. GIF may change colors to fit its palette.

Why flatten the image before writing JPEG?

A new ARGB image starts with transparent pixels. Simply dropping alpha can produce an unwanted background. The flatten() method first paints an opaque background into a TYPE_INT_RGB image, then draws the source over it. The default source-over compositing blends partially transparent pixels with that background.

The JPEG writer receives ordinary RGB pixels. We also use this opaque copy for GIF, BMP, and TIFF so the comparison has a consistent background; this does not mean those formats all have the same transparency capabilities.

The format argument controls encoding: "jpeg" produces JPEG data. The .jpg extension is a useful label for other software, but renaming a PNG file to .jpg does not convert it.

ImageIO.write() returns false when no appropriate writer is found. ImageIO.read() returns null when no registered reader recognizes the data. Both operations can also throw an IOException. Checking these outcomes gives clearer failures than assuming every export succeeded.

The convenience methods use default encoding settings. To control JPEG quality, use an ImageWriter with ImageWriteParam. For animated GIF or multiple-page TIFF output, use the writer’s sequence API where supported; one call to ImageIO.write() is not an animation or multi-page document builder. This example compares pixels and does not preserve source metadata.

What about WebP?

WebP is not one of Java 25’s standard Image I/O formats. A compatible third-party Image I/O provider can add support. Check reading and writing separately: a provider may only implement decoding. After installing a provider according to its documentation, rerun the availability checks. Do not assume an arbitrary WebP library registers an Image I/O writer.

Image I/O discovers service providers on the application class path. ImageIO.scanForPlugins() can rescan it when providers become available after initial discovery. No WebP provider is needed for this tutorial, and the program does not attempt to write WebP.

Try it yourself

Change the flattening background to Color.LIGHT_GRAY, then run the example again. The PNG corner should remain transparent; the other files should show the new background.

Next, print each file’s size using Files.size(path) inside saveAndInspect(). Compare the sizes and inspect the text edges. Repeat with a photograph loaded using ImageIO.read(), keeping the null check. Explain why the smallest format may differ between the drawing and the photograph.

In the next post, we will scale and paint an image in Swing while preserving its aspect ratio.

References