1
        JFrame f = new MnemoticTest();          
        JButton b=new JButton("bat");

        b.setMnemonic(KeyEvent.VK_B);
        f.add(b);
        f.setSize(400, 700);
        f.setVisible(true);

Hello, I got the above code. When it loads, the 'b' is already underlined. I want the 'b' to be underlined only when I click alt.

On loading it should show no underline, and when I click alt, the b should show up as underlined

How do we do it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

2

As I know, this behavior is only supported by the Windows L&F. So you need to change your L&F to Windows L&F.

If you are working on Windows computer, you can do the following:

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        e.printStackTrace();
    }

If not, you can try the following (I'm not sure whether the Windows L&F will work on non-Windows computer):

    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception e) {
        e.printStackTrace();
    }

IMPORTANT: Setting of L&F should be performed on start of application, when no visual elements have been initialized.

Dimitar
  • 4,402
  • 4
  • 31
  • 47
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
  • 1
    *"I'm not sure whether the Windows L&F will work on non-Windows computer"* No it won't. Which is kind of fortunate for users on OS X and Unix/Linux who ***don't want to see** another Windows GUI.* – Andrew Thompson Sep 09 '16 at 09:20
  • @Sergiy Medvynskyy Works well! thank you for your reply. And how do I click alt one, and all Mnemotic stay underlined. And when I click alt once again, all the Mnemotic are no more underlined?? –  Sep 09 '16 at 09:45