Hassan Shahzad Aheer

How to insert image in Jlabel

Created March 12, 2022

In this tutorial we will learn how to set full image in Jlabel. So let's get started.

Open Netbeans go to the project window and click on blank area and then click on new project as you can see in figure #1 or by pressing short cut key Ctrl+N 1.jpg

Figure 1: Create new project Select java application and press Next

2.jpg Figure 2: Select Java Application call the project Set Image In JLable and uncheck the Create Main Class” box and press finish 3.jpg

Figure 3: Title to application now add the form by right-clicking the Source Packages or on the project name and select New>JFrameForm 4.jpg

Figure 4: Add Frame

Enter JLable_Image as the class name and press finish

5.jpg Figure 5 : title to JFrame Form

The JLable :

Jlable is typically used to display text for other graphical components of Graphical User Interface (GUI). it can be found in the Netbeans palette , under swing controls. 6.jpg Figure 6: JLabel

Controls in the NetBeans palette can be dragged onto a form . So click on label to select it keep it held and drag the label onto the form 7.jpg Figure 7: Drag label onto form

set properties of jlabel jlabel>properties 8.jpg Figure 8: Set Properties

set properties

10.jpg Figure 10: Set Border

by right-clicking on jlabel select change variable name a dialog box will appears Notice that by default name for the label is jLabel1

11.jpg Figure 11 : Appears the dialog for change the name of variable 12.jpg Figure 12: change name of variable Type a new name for the jlabel1. Call it lab_img and press OK.

13.jpg Figure 13 : New name for label Now right-click on jlable go to events > mouse > mouseClicked

14.jpg Figure 14: Select mouseClicked event!

to fit image into label we use the method call getScaledInstance() this method allow us to scale the image to the size as we want. Image scaledImage = myimage.getScaledInstance(width, height, Image.SCALE_DEFAULT); add the following code.

JFileChooser select_image = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(“GIF Images”,  “gif”);
        select_image.setDialogTitle(“Select Picture”);
        int result = select_image.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            String select_file = select_image.getSelectedFile().getAbsolutePath();
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Image myimage = toolkit.getImage(select_file);
            Image scaledImage = myimage.getScaledInstance(150, 150, Image.SCALE_DEFAULT);
            ImageIcon icon = new ImageIcon(scaledImage);

now run the program by pressing short cut key ctrl+F6

15.jpg Figure 15: Click on Label when you click on jlabel area a filedialog open select image as you want to add and press open button

16.jpg Figure 16 : Select Image 17.jpg Figure 17 : Result

That's it you are amazing amazing

Let's get in touch on @hshahzadaheer , Linkedin and website