package demo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class FocusDemo extends JFrame {
private JPanel jPanel1;
private JTextArea jTextArea1;
private JTable table;
public FocusDemo() {
initComponents();
customTabBehaviour();
}
private void customTabBehaviour() {
//get the JTable input map:
InputMap inputMap = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
//list the relevant key events:
int[][] list = new int[][]{
{KeyEvent.VK_TAB, 0},
{KeyEvent.VK_RIGHT, 0},
{KeyEvent.VK_RIGHT, KeyEvent.SHIFT_MASK},
{KeyEvent.VK_RIGHT, KeyEvent.CTRL_MASK}};
Object[] keys = new Object[list.length];
for (int i = 0; i < list.length; i++) {
keys[i] = inputMap.get(KeyStroke.getKeyStroke(list[i][0], list[i][1]));
}
//and the associated standard actions:
Action[] actions = new Action[list.length];
ActionMap actionMap = table.getActionMap();
for (int i = 0; i < list.length; i++) {
actions[i] = actionMap.get(keys[i]);
}
//for each standard action put a FocusToComponent Action to the action map:
for (int index = 0; index < list.length; index++) {
final Action standardAction = actions[index];
actionMap.put(keys[index], new FocusToComponent(standardAction));
}
}
private void initComponents() {
table = new JTable();
jPanel1 = new JPanel();
jTextArea1 = new JTextArea();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
table.setModel(new DefaultTableModel(
new Object[][]{
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}},
new String[]{
"Title 1", "Title 2", "Title 3", "Title 4"
}));
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
jPanel1.setPreferredSize(new Dimension(90, 0));
jTextArea1.setColumns(8);
jTextArea1.setRows(10);
jPanel1.add(new JScrollPane(jTextArea1));
getContentPane().add(jPanel1, BorderLayout.EAST);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width - 400) / 2, (screenSize.height - 300) / 2, 400, 300);
}
public static void main(final String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FocusDemo().setVisible(true);
}
});
}
class FocusToComponent extends AbstractAction {
private final Action standardAction;
public FocusToComponent(final Action standardAction) {
super();
this.standardAction = standardAction;
}
public void actionPerformed(final ActionEvent e) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (column < table.getColumnCount() - 1) {
standardAction.actionPerformed(e);
} else {
table.transferFocus();
}
}
}
}