我有一个扩展 AbstractTableModel 的 jtable。我注册了两个 ListSelectionListener,它们获取所选单元格的行和列。但是,当我调用模型中定义的 updateData() 方法,该方法又调用 fireTableDataChanged() 方法时,两个 ListSelectionListener 被触发并且它们获得行和列值 -1,当我使用它们来索引时这是一个异常。有没有办法阻止 fireTableDataChanged() 方法触发两个监听器?或者有没有其他方法可以在不触发所有注册到模型的监听器的情况下更新表数据?
这是代码:
public class MonthTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
//private int currentYear, currentMonth;
private String[] columnName = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 7;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return 6;
}
public void updateData(int y, int m)
{
/**
do something to change the data of the table
*/
fireTableDataChanged();
}
public String getColumnName(int column)
{
return columnName[column];
}
@Override
public Object getValueAt(int row, int column) {
// TODO Auto-generated method stub
if ((row >= 0 && row < 6) && (column < 7 && column >= 0))
return "CalendarDate";
return "";
}
public boolean isCellEditable(int row, int col)
{
return false;
}
TabelMonthModel jTableMonthTable = new TableMonthModel();
SelectionListener listener = new SelectionListener(jTableMonthTable);
jTableMonthTable.getSelectionModel().addListSelectionListener(listener);
jTableMonthTable.getColumnModel().getSelectionModel().addListSelectionListener(listener);
class SelectionListener implements ListSelectionListener {
JTable jtable;
public RowSelectionListener(JTable j)
{
jtable = j;
}
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if (!e.getValueIsAdjusting())
{
int rowIndex = jtable.getSelectedRow();
int colIndex = jtable.getSelectedColumn();
System.out.println("row: " + rowIndex + "\n");
System.out.println("col: " + colIndex + "\n");
}
}
}
谢谢你的帮助