Display Name
Display Name

Reputation: 405

JavaFX Button released event

I have a Button that I want to assign a different action on release to the pressed action. I did this in Swing before using javax.swing.ButtonModel similar to this:

ChangeListener changeListnerUp = new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent event) {

       AbstractButton button = (AbstractButton) event.getSource();
       ButtonModel model = button.getModel();
       boolean pressed = model.isPressed();

       if (pressed) {
           System.out.println( "Up Button pressed, String: " + upString );
       } else
            System.out.println( "Up Button released, String: " + stopString );
       }
    }

};

Can anyone recommend a suitable alternative in JavaFX?

Upvotes: 4

Views: 2727

Answers (2)

fabian
fabian

Reputation: 82461

You could catch multiple events, but in this case there is already a property that is changed according to these events: The pressed property or alternatively the armed property, if leaving the Button with the mouse should cause an event. Simply listen to changes of this property

Example:

The following code animates a Circle as long as the Button is pressed:

@Override
public void start(Stage primaryStage) {
    Circle circle = new Circle(300, 20, 5);
    Timeline animation = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(circle.centerYProperty(), circle.getCenterY())),
            new KeyFrame(Duration.seconds(1), new KeyValue(circle.centerYProperty(), 300))
    );
    animation.setCycleCount(Animation.INDEFINITE);
    animation.setAutoReverse(true);

    Button btn = new Button("Play");
    btn.pressedProperty().addListener((observable, wasPressed, pressed) -> {
        System.out.println("changed");
        if (pressed) {
            animation.play();
        } else {
            animation.pause();
        }
    });

    Pane root = new Pane(btn, circle);

    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}

Upvotes: 2

Hunter Miller
Hunter Miller

Reputation: 21

There is a method from the node class that you can use, called addEventFilters.

exampleNode.addEventFilter(MouseEvent.MOUSE_RELEASED,                
new EventHandler<MouseEvent>() {
                    public void handle(MouseEvent) {  
                    //do stuff here
                 };
              });

Upvotes: 2

Related Questions