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:
The following code saves the current value in the cell
being edited and stops the editing process:
The following code discards any changes made by the user
and stops the editing process:
// 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
}
if (table.getCellEditor() != null) {
table.getCellEditor().stopCellEditing();
}
if (table.getCellEditor() != null) {
table.getCellEditor().cancelCellEditing();
}
Post a comment