Get key combinations

Anonymous picture Anonymous · Jan 13, 2013 · Viewed 15.8k times · Source

How can I get key combination of keys on keyboard E.G. (Ctrl+somekey, Alt+somekey) with Java?

I use KeyEvent listener, MouseEvent listener for all keys on keyboard. I can catch all key event on keyboard by using that listener. But, I cannot catch key combination such as (Ctrl+Alt+Del)....etc.

Answer

Govind Balaji picture Govind Balaji · Jan 13, 2013
public void keyPressed(KeyEvent kevt) {
 if(kevt.getKeyChar()=='c') {
  if(kevt.isAltDown())
  //Code if Alt+c pressed
  if(kevt.isControlDown())
  //Code if Ctrl+c pressed
  if(kevt.isShiftDown())
  //Code if Shift+c pressed
  if(kevt.isAltDown()&&kevt.isControlDown()&&(!kevt.isShiftDown()))
  //Code if Alt+Ctrl+c pressed
  if(kevt.isAltDown()&&kevt.isShiftDown()&&(!kevt.isControlDown()))
  //Code if Alt+Shift+c pressed
  if(!(kevt.isAltDown())&&kevt.isControlDown()&&(kevt.isShiftDown()))
  //Code if Shift+Ctrl+c pressed
  if(kevt.isAltDown()&&kevt.isControlDown()&&kevt.isShiftDown())
  //Code if Alt+Ctrl+Shift+c pressed
}

Use the above code, use any character If you want to check if Alt+C+E is pressed do the following

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.swing.*;

public class Sample implements KeyListener {
  private JTextField lbl=new JLabel("Hello");
  private JPanel pnl=new JPanel(new BorderLayout());
  private JFrame frm=new JFrame ("Sample");
  int []arr;int i=0;

  public Sample() {
    pnl.add("North", lbl);
    frm.setContentPane(pnl);
    frm.pack();
    frm.setVisible(true);
    lbl.addKeyListener(this);
    arr= new int[3];

    public void keyPressed(KeyEvent key) {
       arr[i]=key.getKeyCode();
       i++;
       if((arr[0]==VK_ALT||arr[1]==VK_ALT||arr[2]==VK_ALT)&&   (arr[0]==VK_C||arr[1]==VK_C||arr[2]==VK_C)&&(arr[0]==VK_E||arr[1]==VK_E||arr[2]==VK_E)) {
        //Code you want
       }
     }

     public void keyReleased(KeyEvent evt) {
       arr[i]=null;
     }

     public void keyTyped(KeyEvent kvt) {
     }
 }

}