Berton
Berton

Reputation: 103

JavaFx - How to repeat action as long as button is pressed

From the FXML file I call the up function of the controller. I want to repeat the action as long as the button is pressed. How can I archive this.

Here the up function as example

public void up() {
    gauge.setValue(gauge.getValue()+1);
    System.out.println("up");   
}

Here the part of the

<Button fx:id="btnUp" layoutX="60.0" layoutY="15.0" mnemonicParsing="false" onMousePressed="#up" onMouseReleased="#up" styleClass="style_button_up">
   <font>
      <Font size="18.0" />
   </font>
</Button>
<Button fx:id="btnDown" layoutX="60.0" layoutY="60.0" mnemonicParsing="false" onMousePressed="#down" onMouseReleased="#down" styleClass="style_button_down">
   <font>
      <Font size="18.0" />
   </font>
</Button>

Upvotes: 0

Views: 2227

Answers (2)

Sergey Libedinskiy
Sergey Libedinskiy

Reputation: 101

It is better to use this solution

final AnimationTimer timer = new AnimationTimer() {

            private long lastUpdate = 0;

            @Override
            public void handle(long time) {
                if (this.lastUpdate > 100) {
                    System.out.println(lastUpdate);
                }
                this.lastUpdate = time;
            }
        };

        addEventFilter(MouseEvent.ANY, event -> {
            if (event.getEventType() == MouseEvent.MOUSE_PRESSED)
                timer.start();
            if (event.getEventType() == MouseEvent.MOUSE_RELEASED) {
                timer.stop();
            }

        });

Upvotes: 0

Tobi
Tobi

Reputation: 932

You need to use a Timer for that and start/stop it with Button click.

    final AnimationTimer timer = new AnimationTimer() {

        private long lastUpdate = 0;

        @Override
        public void handle(long time) {
            if (this.lastUpdate > 100) {
                System.out.println("pressed");
            }
            this.lastUpdate = time;
        }
    };

    final Button b = new Button();
    b.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
                timer.start();
            } else {
                timer.stop();
            }

        }
    });

Upvotes: 1

Related Questions