Here are 3 ways to set an icon image in
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
JFrame
. Doing this is dead simple, and each way doesn't take more than one statement. An icon image appears on the title bar at the corner. By default, there will be a java cup. Using the setIconImage(Image)
method, we can set a custom icon image. Here is how we can do this, (with helpful commentaries).
/*
These methods are inherited to JFrame from java.awt.Frame
public void setIconImage(java.awt.Image img);
public Image getIconImage();
*/
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
class SetIconImage extends JFrame
{
public SetIconImage()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Icon image");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// First way, using Toolkit
// The Toolkit class contains a factory method getDefaulToolkit()
// which returns Toolkit object. This object contains getImage()
// method which takes the path of the image and returns the
// java.awt.Image object
setIconImage(Toolkit.getDefaultToolkit().getImage("Java_logo.png"));
// Second way, using ImageIcon
// The getImage() method returns Image instance
// of the ImageIcon, which is exactly what we need
// here
setIconImage(new ImageIcon("Java_logo.png").getImage());
// Third way, using ImageIO
try
{
// The read(), static method of ImageIO class
// takes InputStream object pointing to the image file
setIconImage(ImageIO.read(new FileInputStream("Java_logo.png")));
}catch(Exception e){}
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new SetIconImage();
}
}
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
No comments:
Post a Comment