我有一個擴展AbstractTableModel的一個JTable我ListSelectionListener總是被觸發。我註冊了兩個ListSelectionListeners,它們獲取所選單元格的行和列。然而,當我打電話其中又調用fireTableDataChanged()方法模型中定義的了updateData()方法,兩個ListSelectionListeners被觸發,他們得到的行和列值-1,這是一個異常時,我用它們來索引。反正是有防止fireTableDataChanged()方法來觸發兩個監聽器?還是有沒有其他方法可以更新表格數據而不觸發註冊到模型的所有監聽器?爲什麼當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");
}
}
}
感謝您的幫助