Java Graphics How to - Load ImageIcon from file








Question

We would like to know how to load ImageIcon from file.

Answer

/*from  w w w .  jav  a  2  s . c  om*/
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

import javax.swing.ImageIcon;

public class Main {

  // Image handler
  public static Image getImage(String name) {
      if (name == null || name.isEmpty()) {
          return null;
      }

      URL imageURL = Main.class.getResource(name);
      if (imageURL == null) {
          return null;
      }

      return Toolkit.getDefaultToolkit().createImage(imageURL);
  }
  public static ImageIcon getImageIcon(String name) {
      Image image = getImage(name);
      if (image == null) {
          return null;
      }
      return new ImageIcon(image);
  }
}