Setting the Focus of a JTextField Component Using a JLabel Component

This example associates a label with a text field using setLabelFor(). A mnemonic is set on the label. When the mnemonic keystroke is pressed, the text field will gain the focus.

In the following example, when ALT-L is pressed, the text field gains the focus.

// Create text field JTextField textfield = new JTextField(25); // Create label and associate with text field JLabel label = new JLabel("Text Label"); label.setDisplayedMnemonic(KeyEvent.VK_L); label.setLabelFor(textfield);

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.