I have a simple JFrame
and a JTable
on the frame.
Users can supply data into the rows of the table. One of the requirements is that the new data either can be saved or discarded after closing the frame. I thought that the easiest way to accomplish this behaviour is the following:
override the
setVisible()
method of the frame and clone theDefaultTableModel
's data vector.add a
WindowListener
to the frame and react for theWindowClosing
events. This way, the window listener can decide whether the model should be reset to the model that was saved before.
Here is the relevant code snippet :
@Override
public void setVisible(boolean b) {
//save the original models only if setVisible invoked with true (do not save the model when hiding the frame)
if (b) {
Vector cloned = (Vector) userTableModel.getDataVector().clone();
Vector headerNames = new Vector();
originalModel = new CustomTableModel(cloned, headerNames);
}
super.setVisible(b);
}
Actually, something weird is happening. After I clone the data vector, the table can't be rendered and this leads to the following exception :
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 at java.util.Vector.elementAt(Vector.java:470) at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:650) at asc.model.CustomTableModel.getValueAt(CustomTableModel.java:74) at javax.swing.JTable.getValueAt(JTable.java:2720)
The table is not in connection to the originalModel
in any way. It is a surprise for me because, in theory, the cloning shouldn't affect the table's model. The intention of originalModel is to hold a reference to the newly created copy of the table model. After I commented out the creation of the originalModel
, everything worked fine.
Another interesting thing is when I added an empty String
to the headerNames
vector, the table renderer throws almost the same ArrayIndexOutOfBounds
exception, but with this ending:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
In that case, the first column of the first row rendered perfectly.
My CustomTableModel
is extended from DefaultTableModel
, and it does not use any special method. The constructor simply passes the data vector and the header vector to the superclass.
I hope someone could help to resolve the problem. Thanks in advance.