Java Swing How to - Show image label in Swing thread








Question

We would like to know how to show image label in Swing thread.

Answer

import java.awt.Image;
import java.net.URL;
/*from  w  w w .j  a  va  2 s. c o  m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    final Image img = ImageIO.read(url);

    Runnable r = new Runnable() {

      @Override
      public void run() {
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
      }
    };
    SwingUtilities.invokeLater(r);
  }
}