Monday, August 4, 2008

Override the focus traversal keys of a JTable

In a JTable, there are some predefined focus traversal keys. For example, CTRL+TAB to move out of JTable.

If that needs to be overrided with some other key combination the FocusTraversalKeySet should be replaced with a new set containing the new key combinations.

Following example shows the overriding of ForwardTraversalKey set with new KeySet containing CTRL+Z as the forward traversal key and also BackwardTraversalKey set with an EmptySet to disable all the backward traversals.


JTable table = new JTable(2,2);

TreeSet forwardSet = new TreeSet();

forwardSet.add(AWTKeyStroke.getAWTKeyStroke( KeyEvent.VK_Z,
InputEvent.CTRL_DOWN_MASK
| InputEvent.CTRL_MASK, false ) );

Set unmodifiableForwardSet =
Collections.unmodifiableSortedSet( forwardSet );

// To override the existing forward_traversal_key set
// with new unmodifiable set containing new
// key combination(CTRL+Z)
table.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
unmodifiableForwardSet );

// To disable all the backward traversal keys,
// an empty set can be used
table.setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
Collections.EMPTY_SET );

No comments: