【问题标题】:How to make cells in a column un-selectable如何使列中的单元格不可选择
【发布时间】:2014-04-15 18:16:05
【问题描述】:

我有一个 JTable,其中某些列是不可编辑的。我通过重写 isCellEditable 方法来做到这一点。我现在想让这些列中的单元格不可选。如果用户使用 tab 键浏览单元格,我想集中精力“跳过”这些不可编辑的单元格。你能告诉我这是怎么做到的吗?谢谢。

【问题讨论】:

    标签: java swing jtable selection


    【解决方案1】:

    所有导航行为都由在表格的 actionMap 中注册的操作控制。所以要走的路是挂钩到绑定到 tab 键的操作,实现一个包装器,该包装器根据需要经常调用该操作,并用包装器替换原始操作。

    用于跳过不可编辑单元格的原始代码 sn-p:

    Object actionKey = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
        .get(KeyStroke.getKeyStroke("TAB")); 
    final Action traverseAction = table.getActionMap().get(actionKey);
    Action wrapper = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            traverseAction.actionPerformed(e);
            while(shouldRepeat((JTable) e.getSource())) {
                traverseAction.actionPerformed(e);
            }
        }
    
        private boolean shouldRepeat(JTable source) {
            int leadRow = source.getSelectionModel().getLeadSelectionIndex();
            int leadColumn = source.getColumnModel().getSelectionModel().getLeadSelectionIndex();
            return !source.isCellEditable(leadRow, leadColumn);
        }
    };
    table.getActionMap().put(actionKey, wrapper);
    

    【讨论】:

    • 非常感谢。这真的很有帮助。
    猜你喜欢
    • 2010-12-11
    • 2010-10-20
    • 1970-01-01
    • 2020-02-18
    • 2011-02-08
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多