Programmatically Starting and Stopping Cell Editing in a JTable Component

Normally, the table component automatically starts and stops the editing of table cells based on user input. However, when building table commands, it may be necessary to programmatically enable and disable editing of cells. The following code demonstrates how to set a cell in edit mode:
// Create table int rows = 10; int cols = 5; JTable table = new JTable(rows, cols); // Enable the ability to select a single cell table.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(true); // Set the cell on the 2nd row, 4th column in edit mode int row = 1; int col = 3; boolean success = table.editCellAt(row, col); if (success) { // Select cell boolean toggle = false; boolean extend = false; table.changeSelection(row, col, toggle, extend); } else { // Cell could not be edited }
The following code saves the current value in the cell being edited and stops the editing process:
if (table.getCellEditor() != null) { table.getCellEditor().stopCellEditing(); }
The following code discards any changes made by the user and stops the editing process:
if (table.getCellEditor() != null) { table.getCellEditor().cancelCellEditing(); }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.