简体   繁体   中英

How to add custom keyboard shortcuts to GWT CellTable

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.

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.

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);
    }
}});

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