Java Reference
In-Depth Information
Figure 4-7.
Various JLabel alignments
Figure 4-8.
Various JLabel text positions
JLabel Event Handling
No event-handling capabilities are specific to the
JLabel
. Besides the event-handling capabilities
inherited through
JComponent
, the closest thing there is for event handling with the
JLabel
is the
combined usage of the
displayedMnemonic
,
displayedMnemonicIndex
, and
labelFor
properties.
When the
displayedMnemonic
and
labelFor
properties are set, pressing the keystroke specified
by the mnemonic, along with the platform-specific hotkey (usually Alt), causes the input focus
to shift to the component associated with the
labelFor
property. This can be helpful when a
component doesn't have its own manner of displaying a mnemonic setting, such as with all the
text input components. Here is an example, which results in the display shown in Figure 4-9:
JLabel label = new JLabel("Username");
JTextField textField = new JTextField();
label.setDisplayedMnemonic(KeyEvent.VK_U);
label.setLabelFor(textField);
Figure 4-9.
Using a JLabel to display the mnemonic for another component