Java - How to apply a keyboard shortcut of 3 keys

2019-05-31 16:52发布

问题:

Currently i am using "Ctrl + Space" shortcut to fire a JButton event in my Java code like this :

this.getRootPane().registerKeyboardAction( addStudentButtonActionListener, KeyStroke.getKeyStroke( KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK ), JComponent.WHEN_IN_FOCUSED_WINDOW );

But i want to assign a shortcut of "Shift + Ctrl + Space" for this event instead. How can i do that ?

回答1:

Then use the following key stroke:

KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
    KeyEvent.SHIFT_MASK | KeyEvent.CTRL_MASK)


回答2:

You can use the String format of the KeyStroke

KeyStroke.getKeyStroke("shift ctrl pressed SPACE")

Example

import java.awt.event.*;
import javax.swing.*;

public class TestShiftCtrlSpace {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                JPanel panel = (JPanel)frame.getContentPane();
                InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                im.put(KeyStroke.getKeyStroke("shift ctrl pressed SPACE"), "scs");
                panel.getActionMap().put("scs", new AbstractAction(){
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Shift + Ctrl + Space");
                    }
                });
                frame.setSize(300, 300);
                frame.setLocationByPlatform(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}