Monday, December 6, 2010

How to set an Application Icon in Swing

To set an application icon simply paste this code in you application:

InputStream icon = this.getClass().getResourceAsStream("MyIcon.gif");
if (icon != null) {
   BufferedImage image = ImageIO.read(icon);
   setIconImage(image);
}

Swing components, such as labels and buttons can be decorated with an icon by using the Icon interface: IconImage.


One statement creates the image icon and the other includes the image in the label:

File f = new File("C:\\Image.jpg");

if (f.exists()) {
   BufferedImage image = ImageIO.read(f);
   Icon imageicon = new ImageIcon(image);
   jLabel1.setIcon(imageicon); //Includes the icon
}

Don't forget that you need to include this libraries:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

Need help on something else related ? Ask away ;)

No comments:

Post a Comment