Here you can find the source of addSpaceSelection(final JTable table, final int column)
Parameter | Description |
---|---|
table | the table to add the key listener |
column | the column which has values of boolean class and is editable |
public static void addSpaceSelection(final JTable table, final int column)
//package com.java2s; //License from project: Open Source License import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JTable; import javax.swing.table.TableModel; public class Main { /**//from w w w . j av a 2s. c om * If this table has a editable boolean column, the user can press space to toggle the selection of the selected rows for the column. * @param table the table to add the key listener * @param column the column which has values of boolean class and is editable */ public static void addSpaceSelection(final JTable table, final int column) { table.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE); table.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { TableModel model = table.getModel(); /* * TODO: improve performance if needed * * notes: * beginUpdate + endUpdate will improve performance * but will deselect all selected rows after endUpdate * is called. Therefore currently not used due to unexpected * behaviour. */ //if (model instanceof ThreadSafeDefaultTableModel) { // ((ThreadSafeDefaultTableModel) model).beginUpdate(); //} for (int row : table.getSelectedRows()) { int rowModel = table.convertRowIndexToModel(row); if (model.isCellEditable(rowModel, column)) { model.setValueAt(!(Boolean) model.getValueAt(rowModel, column), rowModel, column); } } //if (model instanceof ThreadSafeDefaultTableModel) { // ((ThreadSafeDefaultTableModel) model).endUpdate(); //} e.consume(); } } }); } }