Stan Reduta
Stan Reduta

Reputation: 3492

Count button clicks with timer in JavaFX

I'm trying to simulate sms application with keyboard input like in older phones where you had to click f.e. button "2" two times to type letter "b", three times for "c" etc. I have several buttons, and for each I need to set some kind of delay so I can click as many times as I want to get needed letter or symbol. I know there is java.util.Timer that can be handy here, but I don't understand how to apply it in this situation and how to turn delay only after first click on "button" not after every next. Below is a sample FXML element I'm using in my code and a method that gets called when a button is clicked.

...
@FXML
Button button_2;

...

public void handleButton2(){
    //Code to execute to count clicks ?
    ...
    //Array of Strings instead of Characters to use .appendText without parsing
    String []letters = {"a", "b", "c", "2"};
    sms_text_area.appendText(letters[/*index of letter*/]);
}
...

Upvotes: 0

Views: 1089

Answers (1)

James_D
James_D

Reputation: 209418

Note that you only want to change the string represented by the button if it was the last one clicked.

In general, to perform something after a delay, use a PauseTransition.

So just introduce some extra fields:

private Button lastButtonClicked ;
private int buttonClickCount ;

private final PauseTransition buttonPressDelay 
    = new PauseTransition(Duration.seconds(0.5));

and then

public void handleButton2(){

    String[] letters = {"a", "b", "c", "2"};

    buttonPressDelay.setOnFinished(e -> {
        sms_text_area.appendText(letters[buttonClickCount]);
        lastButtonClicked = null ;
    });

    if (lastButtonClicked == button_2) {
        buttonClickCount = (buttonClickCount + 1) % letters.length ;
    } else {
        buttonClickCount = 0 ;
    }
    buttonPressDelay.playFromStart();
    lastButtonClicked = button_2 ;
}

Upvotes: 1

Related Questions