0

I created a CellTable in GWT and I set .setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED); to enable the use of keyboad.

Now I can move up and down with keyboard and press spacebar to interact with each row. Is it possible to add custom keyboard shortcuts to this CellTable? For example, I want to change the spacebar to act as the enter button.

Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
v3ctor
  • 105
  • 1
  • 2
  • 10

2 Answers2

1

You can catch any key pressed and do whatever you like. If you override a default behavior of that key, you need to cancel the native event first, then do your actions.

CellTable<Object> myTable = new CellTable<Object>();
// build myTable

myTable.addCellPreviewHandler(new Handler<Object>() {

    @Override
    public void onCellPreview(CellPreviewEvent<Object> event) {
        if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) {
            // Get selected object or objects from your SelectionModel
            // Do something with this object or objects, or
            // do something with the selected row or rows
        }
    }

});

Be careful with the spacebar. It acts as "page down" in some browsers, so users may not expect your custom behavior when pressing it.

Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
  • Sorry but i don't understand can give me a example? in my code i have a addSelectionChangeHandler where i add the method addCellPreviewHandler – v3ctor Dec 28 '12 at 11:40
  • You add this CellPreviewHandler directly to your CellTable widget. Your SelectionChangeHandler is added to your SelectionModel - it should be used to get selected object(s). You don't need to add CellPreviewHandler to your SelectionChangeHandler unless you are trying to modify selection behavior (not recommended). – Andrei Volgin Dec 28 '12 at 12:05
0

1- You should not disable keyboardSelectionPolicy first.

2- You should add this block to constructor or onLoad method:

myTable.addCellPreviewHandler(new CellPreviewEvent.Handler<GuiltyAccusationInfoDto>() {
@Override
public void onCellPreview(CellPreviewEvent<GuiltyAccusationInfoDto> event) {
    if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_UP || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_DOWN
            || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_LEFT || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_RIGHT
            || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_PAGEUP || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_PAGEDOWN) {
        selectionModel.setSelected(listOfData.get(table.getKeyboardSelectedRow()), true);
    }
}});
Hadi Momenzadeh
  • 346
  • 1
  • 4
  • 13