Reputation: 6208
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
Upvotes: 2
Views: 58207
Reputation: 25950
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;
...
}
Upvotes: 5
Reputation: 15434
Try isControlDown
method on KeyEvent
: http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html#isControlDown%28%29
Upvotes: 3
Reputation: 33534
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) {
}
});
Upvotes: 3