How to change the steaming coffee cup icon
Q: How do you change the steaming coffee cup icon that appears in the top left-hand corner of applets and frames?
A: In order to change the icon image on a frame — whether in an applet or an application — you must first create an Image
object. There is more than one way to do this, but here we’ll use the ImageIcon
object, since it has a simple constructor that takes a file name.
ImageIcon image = new ImageIcon("C:/images/your_image.gif");
One you have the ImageIcon
, you call its getImage()
method and pass it to your Frame
‘s setIconImage()
method.
Frame.setIconImage(image.getImage());
It’s worth mentioning that, since Swing’s JFrame
class inherits from the AWT Frame
class, the setIconImage()
method is also available in JFrame
. A complete JFrame
example is included below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AppIconFrame extends JFrame {
public AppIconFrame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
initFrame();
}
//Frame initialization
private void initFrame(){
this.setSize(new Dimension(400, 300));
this.setTitle("Custom Icon");
ImageIcon image = new ImageIcon("c:yourpathyourfile.gif");
this.setIconImage(image.getImage());
}
//Overridden so we can exit on System Close
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if(e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
public static void main(String[] args){
AppIconFrame frame = new AppIconFrame();
frame.setVisible(true);
}
}