How to use the event handler onEditCommit and onEditCancel on JavaFX 2?


Question

I'm trying to make a ListView editable, but when I add the event handlers onEditCommit and onEditCancel in the code I can't change the text in the ListView. Below my code (executed but the edit doesn’t work):

public class ItensTipoStringController implements Initializable {
   @FXML
   private ListView lstItens;
   ArrayList<String> itens = new ArrayList<>();
   ObservableList itensObservaveis = FXCollections.observableArrayList(itens);

   @Override
   public void initialize(URL url, ResourceBundle rb) { 
      itens.add("Evandro");
      itens.add("Miguel");

      lstItens.setEditable(true);        
      lstItens.setCellFactory(TextFieldListCell.forListView());
      lstItens.getItems().addAll(itens);

      lstItens.setOnEditCommit(new EventHandler() {
        @Override
        public void handle(Event event) {
            System.out.println("onEditCommit");
        }
    });

    lstItens.setOnEditCancel(new EventHandler() {
        @Override
        public void handle(Event event) {
            System.out.println("onEditCancel");
        }
    });

    lstItens.setOnEditStart(new EventHandler() {
        @Override
        public void handle(Event event) {
            System.out.println("onEditStart");
        }
    });
   }    

}

1
0
4/30/2013 7:47:57 PM

the edit doesn’t work

You mean that the value of list item didn’t change on the OnEditCommit ?

Of course, you are just printing System.out.println("onEditCommit");

You have to update your item, add this line to your handle method body.

lstItens.getItems().set(event.getIndex(), event.getNewValue());

This gist provides a complete working example, you can find more informations about JavaFX ListView here and here.

5
4/30/2013 11:51:46 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon