java - Robot class - If a Button Is Pressed? -


i have read , understood how robot class in java works. thing ask, how press , release mouse button inside if statement. example make click if (and right after) space button pressed/released. use code:

try {   robot robot = new robot();   if (/*insert statement here*/) {     try {       robot.mousepress(inputevent.button1_mask);       robot.mouserelease(inputevent.button1_mask);     } catch (interruptedexception ex) {}   } } catch (awtexception e) {} 

unfortunately, there isn't way directly control hardware (well, in fact there is, have use jni/jna), means can't check if key pressed.

you can use keybindings bind space key action, when spacebar pressed set flag true, when it's released set flag false. in order use solution, application has gui application, won't work console applications.

action pressedaction = new abstractaction() {     public void actionperformed(actionevent e) {         spacebarpressed = true;     } };  action releasedaction = new abstractaction() {     public void actionperformed(actionevent e) {         spacebarpressed = false;     } };  oneofyourcomponents.getinputmap().put(keystroke.getkeystroke("space"), "pressed"); oneofyourcomponents.getinputmap().put(keystroke.getkeystroke("released space"), "released"); oneofyourcomponents.getactionmap().put("pressed", pressedaction); oneofyourcomponents.getactionmap().put("released", releasedaction); 

then, use

try {     robot robot = new robot();     if (spacebarpressed) {         try {             robot.mousepress(inputevent.button1_mask);             robot.mouserelease(inputevent.button1_mask);         } catch (interruptedexception ex) {             //handle exception here         }     } } catch (awtexception e) {     //handle exception here } 

as ggrec wrote, better way execute mouse press directly when keyboard event fired:

action pressedaction = new abstractaction() {     public void actionperformed(actionevent e) {         try {             robot.mousepress(inputevent.button1_mask);             robot.mouserelease(inputevent.button1_mask);         } catch (interruptedexception ex) {             //handle exception here         }     } }; 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -