1

我创建了一个简单的 JTable,并希望能够在右键单击它并在 JPopupMenu 中选择带有将禁用所选单元格的 JMenuItem 的选项后禁用该单元格,这是我的 MouseAdapter:

private JPopupMenu popup;
private JMenuItem one;

table.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseReleased(MouseEvent e) {
        int r = table.rowAtPoint(e.getPoint());
        if (r >= 0 && r < table.getRowCount()) {
            table.setRowSelectionInterval(r, r);
        } else {
            table.clearSelection();
        }
        int rowindex = table.getSelectedRow();
        if (rowindex < 0)
            return;
        if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
            int rowIndex = table.rowAtPoint(e.getPoint());
            int colIndex = table.columnAtPoint(e.getPoint());

            one = new JMenuItem("Disable this cell");
            popup = new JPopupMenu();
            popup.add(one);
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
    }
});

现在,我知道您可以通过以下方式禁用特定单元格:

DefaultTableModel tab = new DefaultTableModel(data, columnNames) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
};

但这会在创建 JTable 时禁用单元格,但我需要在创建后禁用单元格。关于如何做到这一点的任何想法/线索?

4

1 回答 1

1

您需要修改您的TableModel以添加存储为每个单元格的所需可编辑状态,例如List<Boolean>. 您的模型可以从 中返回存储的状态isCellEditable(),并且您的鼠标处理程序可以在您的TableModel. 您可能需要这里提到的模型/视图转换方法。

于 2013-04-27T13:00:48.053 回答