JavaFx: How to update text of dynimically created TextFields inside GridPane?

前端 未结 2 1022
闹比i
闹比i 2021-01-25 17:51

I\'m developing an app in JavaFx, in which which I\'m dynamically creating TextFeids and CheckBoxes inside GridPane like this:

I\'m adding numbers which user w

2条回答
  •  孤街浪徒
    2021-01-25 18:42

    One way to achieve that is by adding a ChangeListener to every CheckBox in the Table(GridPane), something like this:

    /**
    * This method to change the current value of the TextField at
    * column 3 in the Table(GridPane) by ten 
    * @param table
    */
    private static void changeByTen(GridPane table){
       // loop through every node in the GridPane
       for(Node node : table.getChildren()){
           // and for every CheckBox
           if(node instanceof CheckBox){
              // add change listener to the Selected Property 
              ((CheckBox)node).selectedProperty().addListener((obs, unSelected, selected)->{
                  // get the TextField at third column that corresponds to this CehckBox
                  TextField targetTextFeild = 
                          ((TextField)getComponent(GridPane.getRowIndex(node), 3, table));
                  try{// then try to add/subtract
                      if(selected){// if checked add 10
                         targetTextFeild.setText(String.valueOf(
                             Integer.parseInt(targetTextFeild.getText())+10));
                      }
                      else if(!selected){ // if unchecked subtract 10
                              targetTextFeild.setText(String.valueOf(
                               Integer.parseInt(targetTextFeild.getText())-10));
                      }
                   }catch(Exception e){// do nothing}
               });
            }
        }
    }
    

    Then add this method in the tabPane ChangeListener:

    tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener(){
        ......
        ......
        // I think you have here anchorPane not containerB in the original code
        changeByTen((GridPane) containerB.getChildren().get(0));
    }
    

    Test

提交回复
热议问题