classjavafxclicklong-integerpressed

Create a method for a long click or pressed Button in javafx


In my program I need to make an action when a button is long pressed/click. So I decided to create a method which gets the button in its parameters and return a boolean when the button click is longer than 1 second :

public class EventOperations {

JFXButton button;
boolean result = false;

// Button long click
public EventOperations(JFXButton btn) {
    button = btn;
}

public void isLongPressed() {

    final AnimationTimer timer = new AnimationTimer() {

    private long lastUpdate = 0;

    @Override
    public void handle(long time) {
        if (this.lastUpdate > 2000000000) {
            result = true;
            System.out.println("PRESSED !!!!!!!!!");
        }
        this.lastUpdate = time;
    }
    };

    button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {

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

}

public boolean getIsPressed() {
    return result;
}

}

MAIN.JAVA

EventOperations buttonPressed = new EventOperations(jfxButtonFolder);
buttonPressed.isLongPressed();

But everytime I clicked quickly on the button it shows several "PRESSED !!!" so it doesn't work. The number of 2000000000 is an example. What can I do to get the boolean in my main java method and if it's "pressed" call a function to do something ?

EDIT ! It's work perfectly thank you !


Solution

  • what about just use the start and end times:

    button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
    
            long startTime;
    
            @Override
            public void handle(MouseEvent event) {
                if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
                    startTime = System.currentTimeMillis();
                } else if (event.getEventType().equals(MouseEvent.MOUSE_RELEASED)) {
                    if (System.currentTimeMillis() - startTime > 2 * 1000) {
                        System.out.println("Pressed for at least 2 seconds (" + (System.currentTimeMillis() - startTime) + " milliseconds)");
                    } else
                        System.out.println("Pressed for " + (System.currentTimeMillis() - startTime) + " milliseconds");
                }
            }
        });