BufferedImage img = ImageIO.read(new File("index.jpg"));
Analysis:
this creates a BufferedImage variable called img, We can think of this as an Object which holds the data needed for java to display an image, a BufferedImage as per docs:
The BufferedImage subclass describes an Image with an accessible
buffer of image data. A BufferedImage is comprised of a ColorModel and
a Raster of image data.
This class basically contains methods to help us read and write image without having to write our own each time, As per docs:
A class containing static convenience methods for locating
ImageReaders and ImageWriters, and performing simple encoding and
decoding.
This is a public static method inside ImageIO thus can be accessed without the new keyword. It allows us to read in data of the file we want to use as a Image and returns the data it read in (thus we save it in a variable) as per docs:
Returns a BufferedImage as the result of decoding a supplied File with
an ImageReader chosen automatically from among those currently
registered. The File is wrapped in an ImageInputStream.
Parameters: input - a File to read from.
Returns: a BufferedImage containing the decoded contents of the input, or null.
Throws: IllegalArgumentException - if input is null. IOException - if an error
occurs during reading.
new File(String filename)
is a non static method in the class File and thus has to be accessed with a newly created instance (new). It allows us to create a reference to the file, so that we can perform operations on the File instance (i.e reading writing etc) as per docs:
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
Parameters: pathname - A pathname string
Throws: NullPointerException - If the pathname argument is null
Now when you call setIconImage(img) all the data we read from the file (which is our picture and was converted to an BufferedImage) will be used to display the picture as the JFrames Icon.
Another way to do it is:
// Create frame
String title = "Frame Title";
JFrame frame = new JFrame(title);
// Set icon
Image icon = Toolkit.getDefaultToolkit().getImage("icon.gif");
frame.setIconImage(icon);