【问题标题】:Incrementing by 1 when pressing a button按下按钮时增加 1
【发布时间】:2023-03-05 09:58:01
【问题描述】:

我的代码很长,所以我只会添加相关的 sn-ps。 好的,所以我一直在尝试使用以下代码将标签递增一:

btnComplete.setOnAction(new EventHandler<ActionEvent>() {
         public void handle(ActionEvent e) {

            //if the list has a minimum of 1 item
            if (currentCartTxt.getItems().size() > 0) {
                    int sales=0; 
                    sales++;

                    String x = Integer.toString(sales); 
                    numberOfSalesTxt.setText(x);  

            }
        }});

但是,它只会将我的文本字段更改为 1,而不会增加它。任何帮助将不胜感激。

currentCartTxt 是一个 listView,numberOfSalesTxt 是一个文本字段。

基本上为了解释我的应用程序,我有一个要添加到文本字段 (currentCartTxt) 的项目列表,我需要随时按下完成按钮,但文本字段中必须至少有 1 个项目。每次按下按钮时,textfield(numberOfSalesTxt) 都会增加 1。 谢谢!

【问题讨论】:

  • int sales=0 每次都将值设置为零

标签: java user-interface button javafx actionevent


【解决方案1】:

你必须:

  • 读取当前值(从 Label/View/TextView...)

  • 增加它(只需添加1

  • 设置要查看的新值

if (currentCartTxt.getItems().size() > 0) {
    // get current value
    String text = numberOfSalesTxt.getText();

    // convert it from "String" to "int"
    int sales = Integer.parseInt(text);

    // increment it
    sales++;

    // Convert from "int" to "String"
    String x = Integer.toString(sales);

    // Set new value
    numberOfSalesTxt.setText(x);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2011-12-17
    • 2021-10-13
    相关资源
    最近更新 更多