2

I'm writing small graphics editor and I want catch event when I press Ctrl+A

I use such code (this is test version):

@Override
public void keyPressed(KeyEvent e) {
    System.out.println("Press");
    switch (e.getKeyCode()){
        case KeyEvent.VK_A :
            System.out.println("A");
            break;
    }
}

but I don't know how to catch Ctrl+a

I tryed something like this

    case KeyEvent.VK_CONTROL+KeyEvent.VK_A :
        System.out.println("A+CTRL");
        break;

but this code KeyEvent.VK_CONTROL+KeyEvent.VK_A returns int and maybe another key combination returns the same number

So can someone can help me

Aliaksei Bulhak
  • 6,078
  • 8
  • 45
  • 75

3 Answers3

5

You can use isControlDown() method:

switch (e.getKeyCode())
{
        case KeyEvent.VK_A :
            if(e.isControlDown())
               System.out.println("A and Ctrl are pressed.");
            else
                System.out.println("Only A is pressed");
            break;
        ...
}
Juvanis
  • 25,802
  • 5
  • 69
  • 87
3

Try this.....

f.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if ((e.getKeyCode() == KeyEvent.VK_A) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                System.out.println("woot!");
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    });
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
3

Try isControlDown method on KeyEvent: http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html#isControlDown%28%29

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43