accessibility
Associating a Label with a Component
In this example we are going to see how to associate a Label with a component in a Java Desktop Application. This is a very important step to consider when developing an application that accepts user input especially with text boxes. You have to, somehow, make it clear to the user what kind of input he should provide in a specific text field. For example, a text field that accepts username should be labeled “username”.
Associating a label with a component is very easy as it only requires that you:
- Create a class that extends
JFrame
. - Create a new
TextField
. - Create a new
JLabel
. - Use
setDisplayedMnemonic('N')
to set a mnemonic for the label. - Use
JLabel.setLabelFor
to associate theTextField
with the label.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Component; import java.awt.Frame; import java.awt.Panel; import java.awt.TextField; import javax.swing.JLabel; public class LabelComponentAssociation { public static void main(String[] args) { // Create frame with specific title Frame frame = new Frame("Example Frame"); /* * Create a container with a flow layout, which arranges its children * horizontally and center aligned. A container can also be created with * a specific layout using Panel(LayoutManager) constructor, e.g. * Panel(new FlowLayout(FlowLayout.RIGHT)) for right alignment */ Panel panel = new Panel(); // Create a component to add to the panel; in this case a text field with sample text Component nameField = new TextField("Enter your name"); // Create a component to add to the panel; in this case a label for the name text field JLabel nameLabel = new JLabel("Name:"); // Set a mnemonic on the label. The associated component will get the focus when the mnemonic is activated nameLabel.setDisplayedMnemonic('N'); // make the association explicit nameLabel.setLabelFor(nameField); // Add label and field to the container panel.add(nameLabel); panel.add(nameField); // Create a component to add to the frame; in this case a button Component button = new Button("Click Me!!"); // Add the components to the frame; by default, the frame has a border layout frame.add(panel, BorderLayout.NORTH); frame.add(button, BorderLayout.SOUTH); // Display the frame int frameWidth = 300; int frameHeight = 300; frame.setSize(frameWidth, frameHeight); frame.setVisible(true); } }
This was an example on how to associate a JLabel with a component.