Switching TableModel on a JTable.

Hey guys,

This isn’t relevant to games, at all, but I can’t seem to find any answers on google.

I have a JTable which gets it TableModel changed to another TableModel via the setModel() function on the JTable, but this results in an index out of bounds, because the new TableModel has fewer entries than the old one does.

How on earth do I fix this? It seems like the model is being changed and everything, but for whatever reason, then the JTable decides not to use the old number of entries when calling getValueAt() on the TableModel. :frowning:

Anyone knows of any solutions to this? That doesn’t involve switching table instead of table model. xD

call fireTableDataChanged()

That doesn’t work. I’m still getting index out of bounds. :confused:

Did you implement getRowCount() ?

Just show your model class.

Yeah, it implements getRowCount(). Here’s the relevant functions:


@Override
public int getColumnCount() {
	return LogTableColumn.values().length;
}

@Override
public int getRowCount() {
	return this.logEntries.size();
}

@Override
public Object getValueAt( int rowIndex, int columnIndex ) {
	LogTableColumn col = LogTableColumn.values()[columnIndex];
	LogEntry logEntry = this.logEntries.get( rowIndex );

	Object ret;
	switch ( col ) {
		case TIMESTAMP:
			ret = logEntry.timestamp;
			break;
		case SOURCE:
			ret = logEntry.source;
			break;
		case MESSAGE:
			ret = logEntry.message;
			break;
	}

	return ret;
}

I’ve even printet out debug info in weird places and even though it looks like it’s supposed to, the table still calls the table model with values from the old set.

Then I don’t know without the whole context.
Maybe its repainting while you change the model. Try to queue the change at the end of the AWT thread or something like that.

As 65k mentioned, are you updating the table model on the EDT?

Can you post a simple test class that demonstrates the problem?

Note that if you call stuff such as table.scrollRectToVisible() after changing the model, you’ll have to do so in a SwingUtilities.invokeLater() to allow the table to re-layout first. Just a shot in the dark.