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

南笙酒味 提交于 2019-12-01 12:11:16

问题


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:


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.



来源:https://stackoverflow.com/questions/16300090/how-to-use-the-event-handler-oneditcommit-and-oneditcancel-on-javafx-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!