Sistema de blogs Diarium
Universidad de Salamanca
Pablo Gallardo's Blog
My professional web log about IT, Cybersecurity & Project Management
 

How to add an Icon to a Java application

This are the instructions to add an icon the a Java Swing application.

Icon is loaded from an image. In order to load this image we make use of File and Buffered Image classes.

Icon can be shown in different places, depending on operation system:

  1. On a corner of the window bar, like in Windows. In this example we are adding the icon to the bar of a Java Swing’s JFrame component.
  2. On the system tray, like in Mac OS X.

In this example we put the icon in all the identified places.

Code:
package appicon;
import java.awt.Taskbar;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AppIcon {
public AppIcon() {
//create app frame
JFrame frame;
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel;
panel = new JPanel();
frame.setContentPane(panel);
JLabel label;
label = new JLabel("This Java app has an icon.");
panel.add(label);
//read image
String filepath = "src/appicon/image.png";
File file = new File(filepath);
BufferedImage bImage;
try {
bImage = ImageIO.read(file);
//set icon on JFrame menu bar, as in Windows system
frame.setIconImage(bImage);
//set icon on system tray, as in Mac OS X system
final Taskbar taskbar = Taskbar.getTaskbar();
taskbar.setIconImage(bImage);
} catch (IOException ex) {
Logger.getLogger(AppIcon.class.getName()).log(Level.SEVERE, null, ex);
}
//make frame visible
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new AppIcon();
}
}

pmgallardo

About pmgallardo

I studied Computer Science at University of Salamanca. Since then, I have been working first as developer and then as SAP consutant. This blog is about problems I dealt when using computers, and more important, the solutions I found. Whenever I am on an issue and suddenlly I have a flash that leads me to a solution, I document my discoveries in a post.

, , , , , , , , , , , , , ,

No comments yet.

Leave a Reply


*

Política de privacidad
Studii Salmantini. Campus de excelencia internacional