简体   繁体   中英

Incrementing by 1 when pressing a button

My code is very long so I will only be adding snippets that are relevant. Okay so I've been trying to increment a label by one using the following code:

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);  

            }
        }});

However it only changes my textfield to 1 and never increases it. Any help would be greatly appreciated.

the currentCartTxt is a listView and the numberOfSalesTxt is a textfield.

Basically to explain my app, I have a list of items that I am adding to a textfield (currentCartTxt) and I need to press the complete button whenever but there must be at least 1 item in the textfield. And every time the button is pressed the textfield(numberOfSalesTxt) increases by 1. Thanks!

You have to:

  • read current value (from Label/View/TextView...)

  • increment it (just add 1 )

  • set new value to view

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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