Java Swing Tutorial - Java JLabel.setLabelFor(Component c)








Syntax

JLabel.setLabelFor(Component c) has the following syntax.

public void setLabelFor(Component c)

Example

In the following code shows how to use JLabel.setLabelFor(Component c) method.

// w w w  .j a  va  2  s. c  o  m


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;

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

public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame("LabelFor Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("Username");
    JTextField textField = new JTextField();
    label.setDisplayedMnemonic(KeyEvent.VK_U);
    label.setLabelFor(textField);
    Container box = Box.createHorizontalBox();
    box.add(label);
    box.add(textField);
    frame.add(box, BorderLayout.NORTH);
    frame.add(new JButton("Submit"), BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}