Personalize your application’s icon
Let your user customize the frame
Q: I’ve created a frame that extends from the Frame class. I’d like to change the top-left window icon to a user-defined icon. Is it possible?
A: This question comes up often. Luckily, there is a simple way to set a frame’s icon. If you look at the java.awt.Frame
API, you’ll notice a method:
public void setIconImage(Image image);
To set the frame’s icon, you simply pass the setIconImage()
method an image. (By the way, Swing’s JFrame works the same way, since it directly extends java.awt.Frame
.)
You have a few options for obtaining your icon’s image, but it’s easiest to obtain it from the java.awt.Toolkit
instance:
Toolkit.getDefaultToolkit().getImage("icon_name");
The Toolkit
‘s getImage()
method returns an image.
Calling the setIconImage
on a standard java.awt.Frame
instance works as I outlined above. It should work in your derived class as well. For a user-defined icon you’ll need to pass in an icon name at runtime. Three quick ways to do this are:
- You could simply pass in the full path name of an icon on the command line as an argument. Of course, long startup strings will only annoy your user.
-
You can specify the full path name of an icon as a parameter:
-Dicon=icon_name.gif
When you specify a parameter on the command line you can easily retrieve the value by calling:
System.getProperty("icon")
Properties work through string/value pairs. The
getProperty()
method will return the string value for the key specified on the command line. Again, this is not the best approach, since it will annoy your users. -
You can create a properties file. The properties file is similar to the second solution outlined above. However, instead of specifying the name/value pairs on the command line, specify them inside a file:
your_program.cfg param1=value1 param2=value2 icon=icon_name.gif ... paramN=valueN
To use the configuration file, create a
java.util.Property
instance, open the file with ajava.io.FileInputStream
, and load it into theProperty
by calling theProperty
‘sload()
method. To obtain the icon name, call theProperty
‘sgetProperty()
method and pass it the stringicon
.
However you decide to get the icon name, once you have it, just create the image and pass it onto the frame, as outlined above.