Good evening
I have a JTable that I built with a TableModel how to update the elements of the table, because when I do table = new JTable (new TableProg (elementTab)) I create another table above the original table and it is very ugly
So for example how to update element of table in a loop at each 开发者_Go百科iteration as "elementTab" changes?
thank you very much
Not sure I understand your question.
To update the cells of a table you just use
table.setValueAt(...);
To update the entire table at once you can create a new TableModel and then update the table with the new model:
TableModel model = new YourTableModel(...);
table.setModel( model );
While learning how to use models start with the DefaultTableModel since it also support dynamic changes to the model by using addRow(...) and removeRow().
I recommend you to extend an AbstractTableModel and implement an void addRow(YourObject row)
that fits you. Or if you want to update the hole tables data, you could implement an void addElements(YourCollection elements)
and use the void fireTableDataChanged()
-method.
I.e. keep your data in a LinkedList
and don't forget to use void fireTableRowsInserted(int firstRow, int lastRow)
when you add a new row.
Thanks you so much everyone I solved my problem this way:
model = new TableProg(elements);
table.setModel(model);
in the loop
A little more details on what elementTab is would be very helpful in suggesing a solution. If you want to add rows, simply create an array of objects and add to the model. Eg.
TableModel model = table.getModel();
Object[] row = new Object[] {1,2,3};
model.addRow(row);
if you want to selective update cells, use
model.setValueAt(Object,row,col);
精彩评论