javaswing

How to Create a Key Store for Three Key in Java Swing using getKeyStroke()?


I want to set a Triple Key Accelerator ( which means I need a Triple Key KeyStroke ) for a Menu Item in Java Swing, specifically, Shift + Ctrl + N. My way of setting a key stroke: menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)), this will return a key stroke, Ctrl + N. Is there a way to create a Triple Key KeyStroke so that I can set it as a Menu Item Accelerator. I have read this part of JDK Documentation (Oracle JDK 16 Documentation) but it did not help.


Solution

  • I have read this part of Oracle Documentation:

    static KeyStroke getKeyStroke​(int keyCode, int modifiers)
    

    The key is that the second parameter is "modifiers" (plural).

    So to specify multiple modifiers you "and" the the two modifiers:

    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK, true);
    

    Or, using the following method:

    public static KeyStroke getKeyStroke​(String s)
    

    You would use:

    KeyStroke ks = KeyStroke.getKeyStroke("shift control N");