Search code examples
javakeyboard-shortcutskeypress

Know if pressing a hotkey or shortcut key in Java


How do I detect when a shortcut key Ctrl + A, Ctrl + C or Ctrl + V is pressed and proceed to their shortcut key function. They required me to do it under this function of java, the editor may only listen to the said shortcuts. Is this doable?

TCombo combo = new TCombo();
JTextComponent editor = (JTextComponent) combo.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
    String keyChar = String.valueOf(e.getKeyChar());
    int keyCode = e.getKeyCode();

    //If Ctrl + A
    //do the normal function of select all

    //If Ctrl + C
    //do the normal function of copy

    //If Ctrl + V
    //do the normal function of paste
    }
});

Solution

  • You should use the getModifiers method.

    if ((e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) { 
    //Your code here }
    

    Note that the & operator is used because it's a bit comparison operation.