The following associates a JLabel with a JTextArea and sets a mnemonic that decorates the label. Pressing Alt-X on Windows moves the focus to the JTextArea.
JTextArea textArea = new JTextArea(10, 20);
JLabel label = new JLabel("Text");
label.setLabelFor(textArea);
label.setDisplayedMnemonic(KeyEvent.VK_X);
However, if the label
uses HTML, the label is displayed as expected but it is not decorated with the mnemonic.
JTextArea textArea = new JTextArea();
JLabel label = new JLabel("<html>Text</html>"); //!!! NO DECORATION
label.setLabelFor(textArea);
label.setDisplayedMnemonic(KeyEvent.VK_X);
Is this expected behavior? Any workarounds?
Edit 1 : Modified the example to use a mnemonic that isn't part of the HTML tag based on Aziz' response.
Edit 2 : Removed comments in question about the mnemonic key not working since further experimentation indicated that this was dependent on the Look and Feel used.
BasicLabelUI paints the label differently depending on whether it's got HTML or not. If not, BasicLabelUI's calls some of its own functions that draw the underline. If it does, BasicHTML.Renderer is used, and that does not paint any underlines.
The easiest workaround would be to do this:
JLabel label = new JLabel("<html>Te<u>x</u>t</html>");
maybe because the t
in <html>
is the one that is underlined.
try using setDisplayedMnemonicIndex() to fix that
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.