2

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.

Cheloide
  • 793
  • 6
  • 21
  • Which type of button are you using? Are you using a swing JButton? Could you provide some code? But as you're using actionlistener as it seems, you could check what kind of action was thrown inside the actionPerformed() method. See: [buttonActions](https://docs.oracle.com/javase/7/docs/api/javax/swing/Action.html#buttonActions) – Chiff Shinz Nov 13 '17 at 15:09
  • Also see this question: [JButton long press event](https://stackoverflow.com/questions/23872483/jbutton-long-press-event) – Chiff Shinz Nov 13 '17 at 15:11
  • @ChiffShinz Both those links are about Swing, not JavaFX. – James_D Nov 13 '17 at 15:50

2 Answers2

1

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();
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65
0

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

Ayo K
  • 1,719
  • 2
  • 22
  • 34
  • Doesnt Java have events for pressing and releasing a button? If so, start the timer in the pressing event and stop it in the releasing event. – Manuel Mannhardt Nov 13 '17 at 15:13
  • That is exactly what my answer says @ManuelMannhardt – Ayo K Nov 13 '17 at 15:14
  • Oh my bad then, was confused a bit by your wording. :P – Manuel Mannhardt Nov 13 '17 at 15:19
  • 1
    It would really help, though, if you showed how to execute code when the button is pressed and released, as these methods are not really obvious in JavaFX. Also, what do you mean by "start a timer"? Don't you just need to put the system time in a variable somewhere? – James_D Nov 13 '17 at 15:28