自己想通过方向键控制JTable的焦点移动,最初是通过keyListener,但是却发现只能实现上下的焦点切换,在单元格处于编辑状态时使用左右方向键时根本无法触发监听事件,也就无法实现焦点切换,国内外关于swing的资料都太少了,自己研究了一下国外一个博主提供的代码,然后搜索了一下源码关键词,实现了左右方向键控制焦点的移动。具体原理没有深入研究,希望对需要的同行有所帮助,同样也希望原理的留言告知,谢谢。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53public 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(); } }
代码参考外网:https://www.javaprogrammingforums.com/awt-java-swing/29972-jtable-keybings-defaults-vk_left-vk_right.html
最后
以上就是害羞猎豹最近收集整理的关于JTable通过左右方向键实现焦点切换的全部内容,更多相关JTable通过左右方向键实现焦点切换内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复