简体   繁体   English

JavaFX中带有计时器的计数按钮点击

[英]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 fe 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. 我正在尝试使用键盘输入来模拟短信应用程序,例如在旧手机中,您必须单击两次fe键“ 2”以键入字母“ b”,三次单击“ c”等。我有几个按钮,每个按钮我需要设置某种延迟,以便可以多次单击以获取所需的字母或符号。 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. 我知道这里有java.util.Timer可以派上用场,但是我不明白如何在这种情况下应用它,以及如何仅在第一次单击“按钮”之后而不是在每个按钮之后才打开延迟。 Below is a sample FXML element I'm using in my code and a method that gets called when a button is clicked. 以下是我在代码中使用的示例FXML元素,以及单击按钮时会调用的方法。

...
@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*/]);
}
...

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 . 通常,要在延迟后执行某些操作,请使用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 ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM