tags:

views:

72

answers:

2

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.

+1  A: 

maybe because the t in <html> is the one that is underlined.

try using setDisplayedMnemonicIndex() to fix that

Aziz
Nope. Sorry, should have used a different mnemonic for the example, but even if I change it to 'x' or use setDisplayedMnemonicIndex() (or both) it still doesn't work.I'll edit the example too.
clartaq
+1  A: 

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>");
lins314159
clartaq
Probably because they all inherit from BasicLabelUI. From what I can see, the painting is eventually done by javax.swing.text.html.StyleSheet.
lins314159