Java JTable cancel table cell editing
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; class MyDefaultTableModel extends DefaultTableModel { /* w w w .java 2 s.c om*/ public Class getColumnClass(int mColIndex) { int rowIndex = 0; Object o = getValueAt(rowIndex, mColIndex); if (o == null) { return Object.class; } else { return o.getClass(); } } } public class Main extends JPanel { public Main() { setLayout(new BorderLayout(5, 5)); DefaultTableModel model = new MyDefaultTableModel(); JTable table = new JTable(model); // Add data model.addColumn("Col1", new Object[] { Color.red }); model.addRow(new Object[] { Color.green }); model.addRow(new Object[] { Color.blue }); cancelCellEditing(table); JScrollPane sp = new JScrollPane(table); add(sp, BorderLayout.CENTER); } public static void main(String[] args) { JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main m = new Main(); frame.add(m); frame.setSize(300, 210); frame.setVisible(true); } public static void cancelCellEditing(JTable table) { if (table.isEditing()) { int[] selection = table.getSelectedRows(); table.getCellEditor().cancelCellEditing(); if (selection.length > 0) { selectRows(table, selection); } } } public static void selectRows(JTable table, int[] rowIndexes) { table.getSelectionModel().setValueIsAdjusting(true); try { table.clearSelection(); for (int row : rowIndexes) { table.addRowSelectionInterval(row, row); } if (table.getCellSelectionEnabled()) { table.setColumnSelectionInterval(0, table.getColumnCount() - 1); } } finally { table.getSelectionModel().setValueIsAdjusting(false); } } }