Mnemonics (underlined letters) in pop-up menus in Java Swing in Windows XP

I'm having problems getting underscores to appear sequentially for mnemonics in context menus in a Java Swing application running on Windows XP.

If I right-click, underscores do not appear in the pop-up menu - this is normal, as this behavior is compatible with other Windows applications.

But if I pop up the menu using the menu key (usually next to the right Windows key), the underscores do not appear for my Swing application, whereas they appear for standard Windows applications such as Wordpad and Explorer and the control panel.

The only way I can get underscores is if I hold Alt while right-clicking. Which view is useless, because if someone already clicks on the mouse to right-click, they will not want to use the keyboard to select something in the pop-up window.

Is it possible to display underscores in Swing when the context menu is invoked from a menu key? Without writing my own Look and Feel library?

+3
source share
1 answer
Good question. I just tried this on OS X, and I don't get underlined letters either. Like you, I get them by pressing the alt button (not during the click, but when my popup menu is displayed).

OS X , . , . Google . , .

, , Windows , alt ( , , ). .

, SSCCE, Windows :

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

public class MnemonicTest {
  public static JFrame createUI(){
    JFrame testFrame = new JFrame(  );

    testFrame.add( createLabelWithPopupMenu() );

    testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    testFrame.pack();
    return testFrame;
  }

  private static JLabel createLabelWithPopupMenu(){
    JLabel result = new JLabel( "Right-click me" );
    result.setComponentPopupMenu( createPopupMenu() );
    return result;
  }



  private static JPopupMenu createPopupMenu(){
    JPopupMenu popupMenu = new JPopupMenu(  );
    popupMenu.add( createAction() );
    return popupMenu;
  }

  private static Action createAction(){
    AbstractAction result = new AbstractAction() {
      @Override
      public void actionPerformed( ActionEvent e ) {
        System.out.println( "MnemonicTest.actionPerformed" );
      }
    };
    result.putValue( Action.MNEMONIC_KEY, KeyEvent.VK_A );
    result.putValue( Action.NAME, "Action" );
    return result;
  }

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        createUI().setVisible( true );
      }
    } );
  }
}
0

All Articles