简体   繁体   中英

JavaFX: Enable edit column in a tableview when I press enter

I have a tableview with a editable column called "monto" works fine when edit clicking the mouse, but i need to enable to edit when I press "enter".

 private TableView<Personal> myTable;
 private TableColumn<Personal,Double> columnaMonto;
 ... //Code when user edit with the mouse
         columnaMonto.setOnEditCommit(
            new EventHandler<TableColumn.CellEditEvent<Personal, Double>>() {
                @Override
                public void handle(TableColumn.CellEditEvent<Personal, Double> event) {
                    int pos = event.getTablePosition().getRow();
                    ((Personal)event.getTableView().getItems().get(
                            event.getTablePosition().getRow())
                    ).setImporte(event.getNewValue());

                    myTable.requestFocus();
                    myTable.getSelectionModel().select(pos + 1);
                    myTable.getFocusModel();
               }
           }
    );

This is my attempt:

    myTable.setOnKeyReleased(evt -> {
        if (evt.getCode() == KeyCode.ENTER) {
            System.out.println("Enter is OK!!");

           TablePosition focusedCellPosition = myTable.getFocusModel().getFocusedCell();
           System.out.println(focusedCellPosition.getRow());
           myTable.requestFocus();
           myTable.edit(focusedCellPosition.getRow(), columnaMonto);
        }
   });

The problem is allways is select to edit (like double click) and I need this only if the user press enter. The other problem is here the scroll bar is not working is allways in the same place. Example Img

Thanks and sorry is a little hard to me explain in English.

myTable.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {

            if( event.getCode() == KeyCode.ENTER) {
                return;
        }

            // switch to edit mode on keypress, but only if we aren't already in edit mode
            if( myTable.getEditingCell() == null) {
                if( event.getCode().isLetterKey() || event.getCode().isDigitKey()) {

                    TablePosition focusedCellPosition = myTable.getFocusModel().getFocusedCell();
                    myTable.edit(focusedCellPosition.getRow(), focusedCellPosition.getTableColumn());
                }
            }
        }
});

This code is works fine on pressing of letter key or digit key. Your cell will be edited. For enter key you can write conidition or logic if you can.

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