2021-03-16

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();
    }
}

代码参考外网:https://www.javaprogrammingforums.com/awt-java-swing/29972-jtable-keybings-defaults-vk_left-vk_right.html

具体原理没有做深入研究,swing的资料太少了,有知道原理的可以分享一下。

上一篇:祸及400万用户!Zoom爆出严重漏洞:任何网站可劫持Mac摄像头


下一篇:使用html和css创建静态网页版的个人简历