I have a JTable that tracks the amount of time a person has been waiting to be seated at a restaurant. My problem is that every second, when the timer 'ticks', the selection that is on a row is removed. In other words, if you click a row it becomes highlighted with a blue background and outline, but then when the timer ticks the blue goes away.
ActionListener actListner = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
aTable.updateTime();
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
This is in the main class
public void updateTime()
{
data.updateTime();
fireTableDataChanged();
}
This is in the table model
public void updateTime()
{
Date newTime = new Date();
for (int i = 0; i < startTime.size(); i++)
{
this.setTimeWaiting(i, hoursMin.format(new Date(newTime.getTime() - startTime.get(i).getTime())));
}
}
This is in the data model.
fireTableDataChanged()
tells the table that the data may have changed in any way, and essentially you use it when the entire data set has completely changed (e.g. you've replaced all of the previous contents with new information). The table will redraw itself from scratch and may also clear the selection.Instead, use the more conservative
fireTableCellUpdated(int,int)
and specify each cell that may have been modified due to the time change (presumably, everything in the "wait time" column).You could also use
fireTableRowsUpdated(int,int)
and specify the entire range of rows that have been updated in one call, but generally it's better to stick to the conservative side to minimize unnecessary redraws.