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
Figure 1: Create new project Select java application and press Next
Figure 2: Select Java Application call the project Set Image In JLable and uncheck the Create Main Class” box and press finish
Figure 3: Title to application now add the form by right-clicking the Source Packages or on the project name and select New>JFrameForm
Figure 4: Add Frame
Enter JLable_Image as the class name and press finish
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. 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 Figure 7: Drag label onto form
set properties of jlabel jlabel>properties Figure 8: Set Properties
set properties
- horizontalAlignment = Center
- icon = any Image
- horizontal Size = 150
- opaque = true (checked)
- vertical Size = 150
- border = line border Figure 9: set properties
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
Figure 11 : Appears the dialog for change the name of variable Figure 12: change name of variable Type a new name for the jlabel1. Call it lab_img and press OK.
Figure 13 : New name for label Now right-click on jlable go to events > mouse > mouseClicked
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.setFileFilter(filter);
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);
lab_img.setIcon(icon);
}
now run the program by pressing short cut key ctrl+F6
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
Figure 16 : Select Image Figure 17 : Result
That's it you are amazing
Let's get in touch on @hshahzadaheer , Linkedin and website