Hauptman Koening
Hauptman Koening

Reputation: 69

Check how long was a button pressed

I am making a simulator in which I have a button with different behavior depending on the duration of the press.

If the button is pressed less than 3 seconds, prints nothing, between 3 and 10, prints 1 and higher than 10 prints 2.

Should I try with MouseListener or ActionListener? Any example code would be great! Thanks.

Upvotes: 2

Views: 735

Answers (2)

c0der
c0der

Reputation: 18792

Listen to changes in the pressed property:

public class StageTest extends Application{

    private long startTime;

    @Override
    public void start(Stage primaryStage) {

        Button btn = new Button("Hold");
        Label label= new Label();
        btn.pressedProperty().addListener((obs, wPressed, pressed) -> {
            if (pressed) {
               startTime =  System.nanoTime();
               label.setText("");
            } else {
                label.setText("Button was pressed for "+ (System.nanoTime() - startTime) + " nanos");
            }
        });
        Pane root = new VBox(btn, label);
        Scene scene = new Scene(root, 300, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

Upvotes: 1

Ayo K
Ayo K

Reputation: 1774

A simple hack: Create a timer and start the timer as soon as the button is pressed. Set the interval of the timer to one second then have a counter that increments each time the timer event is fired to keep track of how many seconds it was pressed. As soon as the button is released stop the timer and perform any action you want to

Upvotes: 0

Related Questions