Sometimes , you may want to add an image to a JLabel to beautify your Desktop application which can be done in the following steps :-
1:- Get the width and height of the JLabel and the image you wanna place in it .
2:-If Width and Height of the Label equals the width and the height of the image then there's no need to re-size the image (programatically or manually) else if the width and height of the JLabel is greater that the width and height of the image then chage the JLabels dimension accordingly else if the dimensions(width and height) of the image is greater than the dimensions of the JLabel then use the below code to adjust the Images size
BufferedImage img = ImageIO.read(getClass().getResource(string_path_to_your_image));
Image sci = img.getScaledInstance(your_jlabels_width, your_jlabels_height, java.awt.Image.SCALE_SMOOTH);
Replace string_path_to_your_image with the path to your image file.
Replace your_jlabels_width with the width of your JLabel
Replace your_jlabels_height with the height of your JLabel
* Replcing width and height will ensure that the image fits in the JLabel .
Now Let us understand what the two lines of the code mentioned above are all about ..
BufferedImage img = ImageIO.read(getClass().getResource(string_path_to_your_image));
The above line would read the image from your local hard drive into the img object .
Image sci = img.getScaledInstance(your_jlabels_width, your_jlabels_height, java.awt.Image.SCALE_SMOOTH);
The above line would scale the Image img as per the width and height supplied as parameters to the getScaledInstance( ) method
3 :- Now its time to add the scaled image to the JLbael . JLabel class provide a method setIcon() that takes an ImageIcon object as a parameter .. ImageIcon object can be generated as followns
javax.swing.ImageIcon newIconImage = new javax.swing.ImageIcon(sci);
Now let us pass the ImageIcon object to the JLabel.setIcon() method .. assuming that your JLabel object is jlab .. add the ImageIcon object as follows :-
jlab.setIcon(newIconImage);
Thus an Image is added to the JLabel ..




