By default when the focus in in a JTable then Tab changes focus to the next cell. If the cell is the last one then the 1st cell is focused. Shift-Tab does the opposite.
Assuming we want to move out of the JTable to the next/prev UI component (instead of the next/prev cell) we can do the following to modify the default behaviour:
Set<AWTKeyStroke> forward = new HashSet<AWTKeyStroke>(
myJTable.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
forward.add(KeyStroke.getKeyStroke("TAB"));
myJTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forward);
Set<AWTKeyStroke> backward = new HashSet<AWTKeyStroke>(
myJTable.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
backward.add(KeyStroke.getKeyStroke("shift TAB"));
myJTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backward);
// create the policy which determines what will be the next/prev UI component on Tab/Shift-Tab
class TabFocusTraversalPolicy extends DefaultFocusTraversalPolicy {
private static final long serialVersionUID = 1L;
@Override
public Component getComponentAfter(Container container, Component component) {
Component nextComponent = null;
if(...) {
nextComponent = ...;
} else if(component == ...) {
nextComponent = ...;
} else {
nextComponent = super.getComponentAfter(container, component);
}
return nextComponent;
}
@Override
public Component getComponentBefore(Container container, Component component) {
Component nextComponent = null;
if(...) {
nextComponent = ...;
} else if(...) {
nextComponent = ...;
} else {
nextComponent = super.getComponentBefore(container, component);
}
return nextComponent;
}
@Override
public Component getDefaultComponent(Container container) {
return super.getDefaultComponent(container);
}
@Override
public Component getFirstComponent(Container container) {
return super.getFirstComponent(container);
}
@Override
public Component getLastComponent(Container container) {
return super.getLastComponent(container);
}
}
// install the policy to the JTable
myTable.setFocusCycleRoot(true); // if not true then the policy is not triggered
myTable..setFocusTraversalPolicy(newPolicy);
references:
By default when we click Enter in a JTable where a row is selected then the next row gets the focus.
In order to disable this do the following:
myJTable.getActionMap().put("Enter", new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent ae) {
// override default behaviour which selects the next row
}
});