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
|