java - JavaFX: Make a button look like it's being clicked -


there button in application. clicking results in exact same action pressing key. if user presses key, button being clicked upon, i.e. turn dark short time , go normal again. so, in key handler wrote:

mybutton.fire(); 

which results in action event being fired, not in button looking being clicked upon. how can accomplish latter?

you can use mybutton.arm(...), , mybutton.disarm() "release" it.

since want appear pressed while, , appear released, you'll want along following lines:

mybutton.arm(); pausetransition pause = new pausetransition(duration.seconds(0.5)); pause.setonfinished(e -> mybutton.disarm()); pause.play(); 

and if want fire events when it's released, call mybutton.fire() when call disarm():

pause.setonfinished(e -> {     mybutton.disarm();     mybutton.fire(); }); 

here's sscce. if press "up" key (i.e. cursor key), simulates pressing button:

import javafx.animation.animation; import javafx.animation.keyframe; import javafx.animation.pausetransition; import javafx.animation.timeline; import javafx.application.application; import javafx.beans.property.integerproperty; import javafx.beans.property.simpleintegerproperty; import javafx.geometry.pos; import javafx.scene.scene; import javafx.scene.control.button; import javafx.scene.control.label; import javafx.scene.input.keycode; import javafx.scene.input.keyevent; import javafx.scene.layout.vbox; import javafx.stage.stage; import javafx.util.duration;  public class prgorammaticallypressbutton extends application {      @override     public void start(stage primarystage) {         integerproperty count = new simpleintegerproperty();         label label = new label();         label.textproperty().bind(count.asstring("count: %d"));          button button = new button("increment");         button.setonaction(e -> count.set(count.get()+1));            vbox root = new vbox(5, label, button);         root.setalignment(pos.center);         scene scene = new scene(root, 350, 150);          scene.addeventfilter(keyevent.key_pressed, e -> {             if (e.getcode() == keycode.up) {                 button.arm();                 pausetransition pause = new pausetransition(duration.seconds(0.5));                 pause.setonfinished(evt -> {                     button.disarm();                     button.fire();                 });                 pause.play();             }         });          primarystage.setscene(scene);         primarystage.show();     }      public static void main(string[] args) {         launch(args);     } } 

Comments