对于JTable而言,当你设置列属性为Boolean时,其默认显示出复选框外观,但是如果没有进行设置,是无法实现像 JCheckBox/CheckBox 的勾选功能。
当我在实现这一块的时候,刚开始也不懂,查阅网上资料,都基本只给出代码,而没讲为什么(这倒没什么,关键是代码一大坨,看都看晕),而且更为蛋疼的是,其实现较为复杂(比较主流的是设置CellEditora、CellRenderer)。经过摸索,最后发现其实并不需要那么麻烦,只需:①将要添加的CheckBox功能的单元格的数据类型设置为Boolean ②添加如下代码的前两句即可
【附】效果图及实现代码(含勾选功能的实现):
//设置第0列显示JCheckBox
TableColumnModel tcm = jTable1.getColumnModel();
tcm.getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
//添加标格监听事件
jTable1.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 1){
int columnIndex = jTable1.columnAtPoint(e.getPoint()); //获取点击的列
int rowIndex = jTable1.rowAtPoint(e.getPoint()); //获取点击的行
if(columnIndex == 0) {//第0列时,执行代码
if(jTable1.getValueAt(rowIndex,columnIndex) == null){ //如果未初始化,则设置为false
jTable1.setValueAt(false, rowIndex, columnIndex);
}
if(((Boolean)jTable1.getValueAt(rowIndex,columnIndex)).booleanValue()){ //原来选中
jTable1.setValueAt(false, rowIndex, 0); //点击后,取消选中
}
else {//原来未选中
jTable1.setValueAt(true, rowIndex, 0);
}
}
}
}
TableColumnModel tcm = jTable1.getColumnModel();
tcm.getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
//添加标格监听事件
jTable1.addMouseListener(new MouseAdapter(){
});
转自:http://blog.sina.com.cn/s/blog_6cba238f0101cmrh.html