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.
To avoid GUI freezing, consider using javax.swing.SwingWorker. This class enables background loading of images while keeping the GUI thread alive.
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:
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!