Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key combinations

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.

like image 803
Anonymous Avatar asked Jan 13 '13 08:01

Anonymous


Video Answer


1 Answers

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) {
     }
 }

}
like image 118
Govind Balaji Avatar answered Nov 11 '22 03:11

Govind Balaji