i am using jtable swing, there is checkbox inside jtable of mine, what would be the best way 开发者_JAVA技巧to removeRow of checked checkbox only?
i am using defaultTableModel and removeRow, i need to know how to get the TRUE value of ticked checkbox.
When you set a JCheckBox
to the cell editor, then you can read its value as Boolean
.
class TableModel extends DefaultTableModel {
public TableModel(Object[] headers) {
super(null, headers);
}
public Class getColumnClass(int c) {
switch (c) {
case 0: return Boolean.class;
default: return String.class;
}
}
public boolean isCellEditable(int row, int column) {
if (column == 0) return true;
return false;
}
}
TableModel tableModel = new TableModel(<headers as String []>);
JTable table = new JTable(tableModel);
....
TableColumnModel columnModel = table.getColumnModel();
// setting the first column to use checkboxes
columnModel.getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
...
int rowCount = tableModel.getRowCount();
for(int i=0; i<rowCount; i++) {
Boolean selected = (Boolean)tableModel.getValueAt(0, 0);
if(selected) {
tableModel.removeRow(0);
}
}
If you need to implement the 'Remove all selected' you may consider the following TableModel extension, that will save some repaints (which may give better user experience):
import javax.swing.table.DefaultTableModel;
public class RemoveCheckedRowsTableModel extends DefaultTableModel {
public void removeCheckedRows(int removeCheckBoxColumn) {
int beginRow = 0;
int endRow = 0;
RangeSearch: while (beginRow < dataVector.size()) {
while (getValueAt(beginRow, removeCheckBoxColumn).equals(Boolean.FALSE)) {
beginRow++;
endRow++;
if (beginRow >= dataVector.size()) {
break RangeSearch;
}
}
while ((endRow + 1) < dataVector.size()
&& getValueAt((endRow + 1), removeCheckBoxColumn).equals(Boolean.TRUE)) {
endRow++;
}
for (int i = beginRow; i <= endRow; i++) {
dataVector.removeElementAt(beginRow);
}
fireTableRowsDeleted(beginRow, endRow);
endRow = ++beginRow;
}
}
}
精彩评论