Java - How to apply a keyboard shortcut of 3 keys

2019-05-31 17:00发布

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 ?

2条回答
Evening l夕情丶
2楼-- · 2019-05-31 17:27

Then use the following key stroke:

KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
    KeyEvent.SHIFT_MASK | KeyEvent.CTRL_MASK)
查看更多
3楼-- · 2019-05-31 17:40

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);
            }
        });
    }
}
查看更多
登录 后发表回答