Link JLabel with other component - Java Swing

Java examples for Swing:JLabel

Introduction

You use use three methods setText(), setDisplayedMnemonic(), and setLabelFor() to link one JLabel to another component.

setText() method sets the text for the JLabel.

setDisplayedMnemonic() method sets a keyboard mnemonic for the JLabel.

setLabelFor() method accepts a reference to another component and it indicates that this JLabel describes that component.

setDisplayedMnemonic() and setLabelFor() work in tandem.

When the mnemonic key for the JLabel is pressed, the focus is set to the component that was used in the setLabelFor() method.

Demo Code

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main extends JFrame {

  public Main() {
    super("JButton Clicked Counter");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create a JTextField where the user can enter a name
    JTextField nameTextField = new JTextField("Please enter your name...");

    // Create a JLabel with N as its mnemonic and nameTextField as its label-for
    // component//from w  w  w .j a  va2s.  c  o m
    JLabel nameLabel = new JLabel("Name:");
    nameLabel.setDisplayedMnemonic('N');
    nameLabel.setLabelFor(nameTextField);

    // Add name label and field to a container, say a contentPane
    add(nameLabel);
    add(nameTextField,BorderLayout.SOUTH);

  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials