5.3 Adding labels
You can add a label element to a GUI using the JLabel class. This element is used to display user-invariant text or image, or both. A JLabel object is created using the new keyword, and its constructor takes a string argument that specifies the text to display on the label, or the name of an ImageIcon object that represents the image to display. It can also take three arguments specifying text, image, and horizontal anchoring as a JLabel constant. For example, JLabel (“text”, img, JLabel.CENTER) binds to the center. If the JLabel object contains text and an image, then the relative position of the text can be determined by specifying the JLabel constant as an argument to the setVerticalPosition () and setHorizontalPosition () methods of the JLabel object. There is an additional ToolTip element – a tooltip that appears when you hover the mouse cursor over an object. It can be created using the setToolTipText () method, giving it a string of text with a hint as an argument.
1.Edit the copy of the Window.java file, replacing the class name Window in declaration, constructor, and instance to Labels.
2. Before the Labels () constructor, create an ImageIcon object for the image.
ImageIcon duke = new ImageIcon (“duke.png”);
3.Next, create three JLabels: one for displaying an image, one for displaying text, and a third for both.
JLabel lbl1 = new JLabel (duke);
JLabel lbl2 = new JLabel (“Duke is the talisman of Java technology.”);
JLabel lbl3 = new JLabel (“Duke”, duke, JLabel.CENTER);
4. Inside the Labels () constructor, add the following statement to create a hint for the first label.
lbl1.setToolTipText (“Duke is the Java mascot”);
5.After the third label, write two operators to anchor the text center and bottom.
lbl3.setHorizontalTextPosition (JLabel.CENTER);
lbl3.setVerticalTextPosition (JLabel.BOTTOM);
6.Now add three operators to add components
JLabel to JPanel container.
pnl.add (lbl1);
pnl.add (lbl2);
pnl.add (lbl3);
7.Save the program as Labels.java, then compile and run by hovering over the first label
If you intend to distribute the program in single Java archive, before creating the ImageIcon object graphic resources must be loaded using the ClassLoader object. The getResource () method of the ClassLoader object needs to specify the filename or a path to it, and the method will return a URL that can be used as an argument to the ImageIcon constructor.
8.Before the Labels () constructor, create a ClassLoader object.
ClassLoader ldr = this.getClass (). GetClassLoader ();
9. Edit the ImageIcon () constructor presented in
Step 2 to load the URL of the resource file using the ClassLoader object.
ImageIcon duke =
new ImageIcon (ldr.getResource (“duke.png”));
10.Save changes, then re-compile and run program. It can now be redistributed in a JAR file.