Use JLabel Mnemonics to Interconnect a specific JLabel and JTextField in Java

Description

The following code shows how to use JLabel Mnemonics to Interconnect a specific JLabel and JTextField.

If you pass HTML tags to the setText method on a JLabel, the tags must start with "<html>" and end with "</html>".

Example


import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
/*from   w w w .  ja  v  a2 s  .  c o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Use JLabel Mnemonics to Interconnect a specific JLabel and JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer