mardi 3 octobre 2017

Proper way to access exteranl non-final variable from ChangeListener in JAVA

I am creating several checkboxes in a loop. According to a few tutorials I have read I need to create a new ChangeListener for each one. Once the change takes place I call a method to handle the change.

The problem is that I need to access or pass in an indexing variable so that the ChangeListener can send it to the method that handles it.

The code I have so far:

//Set an indexing variable I can use as a key for my checkbox map elsewhere
int i = 0;

for(LocalDate date : specials.getDates()){
    String displayDate = date.format(formatter);
    CheckBox cb = new CheckBox(displayDate);

    cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean checkValue) {                        
                handleDateCheck(date, checkValue, i);
                //I can access the date object here but not the int i because it is not final
               //I have looked and tried many different searches but can not find an example of how to handle this change event correctly.
        }
    });

    this.syncDates.getChildren().addAll(cb);
    i++;        
}

public void handleDateCheck(LocalDate date, boolean checkValue, final int i){
        if (checkValue){
            this.selectedDates.put(i, date);
        }
        else{
            this.selectedDates.keySet().removeIf(s -> s.equals(i));
        }
        System.out.println("map"+this.selectedDates);
    }




Aucun commentaire:

Enregistrer un commentaire