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:
- 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.
- 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();
}
}