JTable通过左右方向键实现焦点切换
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();
}
}
具体原理没有做深入研究,swing的资料太少了,有知道原理的可以分享一下。