Vince
Vince

Reputation: 15128

JLabel keyboad alternative

The first paragraph of the JLabel API documentation states:

"A label does not react to input events. As a result, it cannot get the keyboard focus. A label can, however, display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it."

I'm pretty sure I understand the concept of not being able to gain focus for keyboard events. What I'm not sure about is what it means when it says "A label can display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it".

What is a keyboard alternative? Why wouldn't a nearby component be able to display it? How does a label display a keyboard alternative for a near-by component?

Upvotes: 0

Views: 629

Answers (2)

camickr
camickr

Reputation: 324207

How does a label display a keyboard alternative for a near-by component?

Say you have a label "First Name" followed by a text field. You can use:

JTextField textField = new JTextField(10);
JLabel label = new JLabel("First Name");
label.setLabelFor( textField );
label.setDisplayedMnemonic(KeyEvent.VK_F);

Now when the user uses Alt-F focus will be placed on the related text field.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347332

What it means is, with a combination of JLabel#setDisplayedMnemonic and JLabel#setLabelFor you can configure the label to display a short cut key to the user that when activiated, with transfer focus to the associated component.

The mnemonic is a single character within the text of the label, which when the activation key is held down (Alt on windows), will allow the user to transfer focus to the associated field.

For example, if you had a label with the text First name:, you could set the mnemonic to F, which would allow the user to press Alt+F to focus the associated field.

Under windows, when you hold down the Alt key, it will display an underscore character under the mnemonic character. So Look and Feels will always display this underscore and some may highlight the fact in other ways

Upvotes: 2

Related Questions