Ziggy Pop
Ziggy Pop

Reputation: 11

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.

Upvotes: 0

Views: 854

Answers (1)

Hello World
Hello World

Reputation: 57

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.

Upvotes: 0

Related Questions