Leon Anavi
IT Tips && Tricks

Java

Created: 16.07.2009 08:48 Last Modified: 18.08.2009 14:31 Views: 15142
Keywords: GUI, Image, JLabel, swing

How to Load Image At Java Swing Application

This tutorial describes a simple way to load an image from file in standalone Java 2 application with swing graphical user interface. Let us assume there is an existing application with swing GUI and insert a instance of class javax.swing.JLabel named as jLabelImage. The following packets must be imported in order to manage files, load and display images:
import java.io.File;
import java.awt.Image;
import javax.imageio.ImageIO;
At an appropriate location at the code read the image file and load it as an icon of the label.
try 
{
  // Read from a file
  File FileToRead = new File("/path/image");
  //Recognize file as image
  Image Picture = ImageIO.read(FileToRead);
  //Show the image inside the label
  jLabelImage.setIcon(new ImageIcon(Picture));
} 
catch (Exception e) 
{
  //Display a message if something goes wrong
  JOptionPane.showMessageDialog( null, e.toString() );
}

More information about the used methods and the thrown exceptions is available at:

Class File
Class Image
Class ImageIO

  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.