JavaFX Button Event Issued

I have Buttonone that I want to assign to another action when releasing the clicked 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?

+4
source share
2 answers

You can catch several events, but in this case there is already a property that changes in accordance with these events: the property pressedor, alternatively, the property armed, if left Buttonwith the mouse, should trigger an event. Just listen for changes to this property.

Example:

Circle , Button:

@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();
}
+2

node, , addEventFilters.

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

Source: https://habr.com/ru/post/1650993/


All Articles