I have created a simple JTable and wish to be able to disable a cell after right clicking it and selecting the option in the JPopupMenu with a JMenuItem that will disable the selected cell, here's my 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());
}
}
});
Now, I know you can disable particular cell(s) by doing:
DefaultTableModel tab = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
but this is disabling the cell on creation of JTable but I need to disable the cell after creation. Any ideas/leads on how this can be done?
You'll need to modify your TableModel
to add storage for the desired editable state of each cell, e.g. List<Boolean>
. Your model can return the stored state from isCellEditable()
, and your mouse handler can set the desired state in your TableModel
. You may need the model/view conversion methods mentioned here.