Localized accelerators (JMenuItem hotkeys) in Swing

感情迁移 提交于 2019-12-04 02:16:19

问题


I am working in an English app on a german laptop, over a spanish OS.

Even if I explictly set Locale.setDefault(Locale.ENGLISH) at the beggining of my app, I am seeing the hotkexs in the menu as

CTRL + Mayúsculas + C 

instead of

CTRL + SHIFT + C 

that I passed to the KeyStroke object.

Is not only that word does not get localized to english as I specified, but also that it maps SHIFT key to MAYUS (CAPS LOCK in english), so I guess this is not only a language issue, but keymap´s as well.

So how can I impose english for all the GUI components?

Thank you!


回答1:


You have to make sure that you set the locale before any toolkit code is executed. The following code shows the effect: if you move the Locale.setDefault(Locale.GERMAN); to any other line it will show the default accelerator names again.

Instead of setting the locale inside your code you may also append the following argument to the VM:

-Duser.language=DE

public class MenuLocale {

    public static void main(String[] args) {
        Locale.setDefault(Locale.GERMAN);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                JMenuBar menubar = new JMenuBar();
                JMenu menu = new JMenu("Menu");
                JMenuItem menuitem = new JMenuItem("Menuitem");    
                menuitem.setAccelerator(KeyStroke.getKeyStroke('X', KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK));

                f.setJMenuBar(menubar);
                menubar.add(menu);
                menu.add(menuitem);

                f.pack();
                f.setVisible(true);
            }
        });
    }
}


来源:https://stackoverflow.com/questions/10952130/localized-accelerators-jmenuitem-hotkeys-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!