我想在一個JTable中單擊一個複選框更改值。下面是我在的MouseListener排序JTable的rowAtPoint(點)的返回值
public void mouseClicked(MouseEvent e) {
Point mouse = e.getPoint();
int row = table.rowAtPoint(mouse);
int col = table.columnAtPoint(mouse);
if (col == 0) tableModel.setValueAt(new Boolean(!(Boolean) tableModel.getValueAt(row, col)), row, col);
}
的問題是,當我對錶進行排序,出現這種情況
這裏是一個SSCCE
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
@SuppressWarnings("serial")
public class SSCCE extends JFrame {
JTable table;
public SSCCE() {
setSize(300, 200);
Object[][] data = { {false, "This is false"}, {true, "This is true"}};
table = new JTable(new CustomTableModel(data));
add(table);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private class CustomTableModel extends AbstractTableModel {
Object[][] data;
public CustomTableModel(Object[][] data) {
this.data = data;
}
public Class<?> getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
public int getColumnCount() {
return data[0].length;
}
public int getRowCount() {
return data.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SSCCE();
}
});
}
}
使用的代碼
有沒有辦法解決這個問題?或者更好的方法(而不是ListListener)來檢測單元格上的點擊?
找到解決方案在[如何添加複選框到JTABLE擺動](http://stackoverflow.com/questions/7391877/how-to-add-checkboxes-to-jtable-swing)在你的情況下工作正常,因爲好。你根本不需要添加鼠標監聽器。 – Braj
我想你的問題是你沒有在你的自定義模型中實現'setValueAt(...)'方法,所以編輯器不能保存更新的值。沒有理由創建自定義TableModel。你可以使用'DefaultTableModel'並重寫'getColumnClass(...)'方法。 – camickr
請勿使用[data [0] [columnIndex] .getClass()]來確定列的類型!如果值爲空會發生什麼?在排序時,您需要在視圖和模型索引之間進行轉換 – MadProgrammer