bitsforbits
bitsforbits

Reputation: 21

How to make Java Vaadin 24 Grid Cell Ready to Edit By Pressing a Key

I'm trying to make my Java Vaadin (V24) grid more easily editable. My goal is to have the cell I navigate to ready to be edited by pressing a key (Key A for example).

The problem is there seems to be no direct command to make a cell ready to be edited at once.

editor.editItem(currentItem.get());

only opens the editor but it is not possible to proceed with editing directly.

I also cannot find a way to save the currently focused item since it must be an Optional which means I cannot use that in further functions that easily.

Any suggestions would be appreciated, thanks.

Upvotes: 1

Views: 84

Answers (1)

Drew Harvey
Drew Harvey

Reputation: 166

If I understand correctly, you want to have some kind of key input that will toggle a row to become editable. Here is a demonstration of using the Vaadin Shortcuts API to perform this with the keys 'CTRL' + 'A':

var grid = new Grid<Person>();

// setup column editor components
var binder = new Binder<Person>();
grid.getEditor().setBinder(binder);

var nameEditor = new TextField();
binder.bind(nameEditor, Person::getName, Person::setName);

var ageEditor = new TextField();
binder.bind(ageEditor, Person::getAge, Person::setAge);

// setup the grid
grid.addColumn(Person::getName)
        .setEditorComponent(nameEditor);
grid.addColumn(Person::getAge)
        .setEditorComponent(ageEditor);
grid.addComponentColumn(person -> 
    new Button("Show Bean Value", e -> Notification.show(person.toString())));

// CTRL + A toggles the selected rows editor
Shortcuts.addShortcutListener(this,
                () -> {
                    var editItem = grid.getEditor().getItem();
                    var selectedItem = grid.getSelectedItems().stream().findFirst().orElse(null);
                    grid.getEditor().closeEditor();
                    if (editItem != selectedItem) {
                        grid.getEditor().editItem(selectedItem);
                        nameEditor.focus();
                    }
                },
                Key.KEY_A, KeyModifier.CONTROL)
        .listenOn(grid);

// add some dummy data
grid.setItems(
        new Person("Jeff", "20"),
        new Person("Tom", "23")
);


// person pojo class
public static class Person {
   private String name;
   private String age;
   //... getters and setters
}

Some additional notes:

  • Using a modifier key, such as CTRL, ensures that you don't need to handle stepping on standard input
  • grid.getEditor().closeEditor() allows you to immediately toggle off editing and write the current editor field value to the bean
  • grid.addCellFocusListener(...) can be useful if you want to track what specific cell is currently targeted (potentially you could auto-focus the correlating editor component when CTRL + A is entered)

Upvotes: 0

Related Questions