How to determine if some key is pressed with CTRL?

Answered

Hello, I am writing a little plugin in which I want to trigger the searching (from a SearchTextField object) once  CTRL+V  or ENTER is pressed, and I've already made it work with pressing  ENTER, but not CTRL+V .

(Why not JBTextField: I want the UI of SearchTextField  ¯\_(ツ)_/¯)

My codes :

SearchTextField searchTextField = new SearchTextField();
searchTextField.addKeyboardListener(
                new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                         if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_V) {                                                          
                             // do search -> never reached
                         }else if(e.getKeyCode() == KeyEvent.VK_ENTER){
                             // do search -> can be reached
                         }
                    }
                }
);

I printed out the value of e.isControlDown() and e.getKeyCode(), and when I press CTRL+V  it's something like this:

true, 17   // represents "CTRL" ?

It never show what's been pressed WITH CTRL.

 

I tried keyReleasedas well, It's been invoked twice, and the output is :

false, 17
false, 86  // represents "V"

It's not abled to know whether CTRL is down when KeyCode is V.

I figured that I can use keyReleased with a field (of KeyAdapter class) to store my last key to do the job? But that doesn't sound right, for I think there's a natural way to do it.

0
3 comments

Hardcoding CTRL+V as a shortcut for paste is not guaranteed to work on all systems.

Why do you need this functionality? Does it work if you override keyReleased() in addition?
https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

0

Thanks for your reply.

Q: Why do you need this functionality?

A: Just like the “SpeedSearch” thing in intellij's framework, I want the searching to be triggered right after users paste the content. It's not necessary, but it will be a better experience for them, because they will use copy&paste (instead of typing) into this TextField in most cases. 

Q: Does it work if you override keyReleased() in addition?

A: As I metioned in my question, simply overriding keyReleased()  does not work, for I can't know whether CTRL is down when KeyCode is V. And it's hard to predict the order that users release these two keys.  

 

If there's no natural ways to do this, simply listening to ENTER is indeed enough.

0

Sorry for long delay, please try this suggestion.

 

Add listener via SearchTextField#addDocumentListener and catch insertUpdate. Then check length via event.getLength > 1  and trigger the searching. It won't work if one letter was pasted, though.

0

Please sign in to leave a comment.