Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use KeyEvent

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

like image 845
Aleksei Bulgak Avatar asked Feb 02 '26 08:02

Aleksei Bulgak


1 Answers

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;
        ...
}
like image 113
Juvanis Avatar answered Feb 03 '26 20:02

Juvanis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!