Link to home
Start Free TrialLog in
Avatar of brent_watson
brent_watson

asked on

Update JTable using a multidimensional array

I've been Googling for an answer for about an hour with no luck, so I thought I would see if anybody has some insight for me...

I have a program, wherein I create a JTable using the constructor that takes a multidimensional array of data and an array of column headings

I.E.:
Object[][] myData = {{"test1", "test1"}, {"test2", "test2"}};
String[] colHeadings = {"Col 1", "Col 2"};
myJTable = new JTable(myData, colHeadings);

The array (myData) contains a list of files from a directory.  What I am trying to accomplish is changing the array and having the changes reflect in the JTable.  Where I am getting stuck is if the new data is longer than the old (array held list of 2 files now has 3 files).

I.E.:
If I do this, JTable displays my changes as I want:
myData[0][0] = "Test Change";
AbstractTableModel myAbsModel= (AbstractTableModel)myJTable.getModel();            myAbsModel.fireTableDataChanged();  //(OR myAbsModel.fireTableRowsUpdated(x, y);  works too

But, if I need to change the size of the array, which will move the reference to a different object, this stops changes from reflecting in myJTable

I.E.: ...This dosen't to work! :-( ...
Object[][] updatedList = getFileList(); // Returns Object[][] of data for files
myData = (Object[][])updatedList.clone();  // Copy new list into Array linked to JTable
myData[0][0] = "Test Change";
AbstractTableModel myAbsModel= (AbstractTableModel)myJTable.getModel();            myAbsModel.fireTableDataChanged();

...Now, hopfully I didn't make something easy sound confusing...

Can anyone suggest a better way to update the data in myJTable with new data from a different array (that could be different size? [More records, no change in #columns]).

Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of hoomanv
hoomanv
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
DefaultTableModel is capable of data resizing
with this method you can change the data array
setDataVector(Object[][] dataVector, Object[] columnIdentifiers)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of brent_watson
brent_watson

ASKER

Exellent.  Worked like a charm.  Thanks.
:-)

>>use javax.swing.table.DefaultTableModel as your table model

You were already doing so ;-)