Home >Java >javaTutorial >How to Avoid GUI Freezing While Loading Images in Swing?

How to Avoid GUI Freezing While Loading Images in Swing?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 03:33:02437browse

How to Avoid GUI Freezing While Loading Images in Swing?

Display Images Using SwingWorker

Problem: Freezing GUI While Loading Images

When an image is loaded from the web to a panel, the GUI can freeze until the loading process is complete. This can be annoying for users.

Solution: Using SwingWorker

To avoid GUI freezing, consider using javax.swing.SwingWorker. This class enables background loading of images while keeping the GUI thread alive.

Implementation

The following example demonstrates how to use SwingWorker to load images:

import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

public final class WorkerTest extends JFrame {

    private final JLabel label = new JLabel("Loading...");

    public WorkerTest() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label.setHorizontalTextPosition(JLabel.CENTER);
        label.setVerticalTextPosition(JLabel.BOTTOM);
        this.add(label);
        this.pack();
        this.setLocationRelativeTo(null);
    }

    private void start() {
        new ImageWorker().execute();
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(() -> {
            WorkerTest wt = new WorkerTest();
            wt.setVisible(true);
            wt.start();
        });
    }

    class ImageWorker extends SwingWorker<Image, Void> {

        private static final String TEST
            = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";

        @Override
        protected Image doInBackground() throws IOException {
            Image image = ImageIO.read(new URL(TEST));
            return image.getScaledInstance(640, -1, Image.SCALE_SMOOTH);
        }

        @Override
        protected void done() {
            try {
                ImageIcon icon = new ImageIcon(get());
                label.setIcon(icon);
                label.setText("Done");
                WorkerTest.this.pack();
                WorkerTest.this.setLocationRelativeTo(null);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

In this example:

  • The ImageWorker class extends SwingWorker to handle loading and resizing the image.
  • The overridden doInBackground() method loads the image from a URL and scales it to the desired size.
  • The overridden done() method updates the label's icon and text when the image loading is complete, and resizes and repositions the frame accordingly.
  • The btn_TrackbusActionPerformed method in the provided code can be modified to call the start() method when the button is clicked, initiating the image loading process in the background.

By using SwingWorker, the image loading process can run in the background, allowing the GUI to remain responsive while the image is being fetched and displayed.

The above is the detailed content of How to Avoid GUI Freezing While Loading Images in Swing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn