自己想通过方向键控制JTable的焦点移动,最初是通过keyListener,但是却发现只能实现上下的焦点切换,在单元格处于编辑状态时使用左右方向键时根本无法触发监听事件,也就无法实现焦点切换,国内外关于swing的资料都太少了,自己研究了一下国外一个博主提供的代码,然后搜索了一下源码关键词,实现了左右方向键控制焦点的移动。具体原理没有深入研究,希望对需要的同行有所帮助,同样也希望原理的留言告知,谢谢。
public class Sample {
private JFrame frame;
private JPanel panel;
private JTable table;
public Sample() {
initComponents();
}
public void initComponents() {
frame = new JFrame();
panel = new JPanel();
table = new JTable(50, 5);
registerTableActionMap();
table.setColumnSelectionAllowed(true);
table.setPreferredSize(new Dimension(400, 400));
panel.add(table);
frame.getContentPane().add(panel);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* 注册表格的ActionMap
*/
private void registerTableActionMap(){
final Action leftAction = table.getActionMap().get("selectPreviousColumn");
table.getActionMap().put("selectPreviousColumn", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
leftAction.actionPerformed(e);
int selRow = table.getSelectedRow();
int selCol = table.getSelectedColumn();
table.editCellAt(selRow, selCol);
}
});
final Action rightAction = table.getActionMap().get("selectNextColumn");
table.getActionMap().put("selectNextColumn", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
rightAction.actionPerformed(e);
int selRow = table.getSelectedRow();
int selCol = table.getSelectedColumn();
table.editCellAt(selRow, selCol);
}
});
}
public static void main(String[] args) {
new Sample();
}
}