I have a JTable which contains TableModel(all my data). The JTable has multiple rows and columns. I need to shuffle the rows randomly. I understand I can do that with
Collections.shuffle(some list from TableModel);
But I dont know how to get the list from the existing JTable which had TableModel.
on somebodies suggestion, I tried this
RowSorter<? extends TableModel> sorter = mDocListTable.getRowSorter();
ArrayList<RowSorter.SortKey> list = new ArrayList<RowSorter.SortKey>();
list.add(new RowSorter.SortKey(0, SortOrder.DESCENDING));
Collections.shuffle(list);
sorter.setSortKeys(list);
but didnt work.
Something like this could work?
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.getDataVector().sort((Object o1, Object o2) -> Math.random() > 0.5 ? -1 : 1);
model.fireTableDataChanged();
Edit:
For Java-7
and since .sort()
was not implemented until Java-8
, a 2nd (and maybe more readable) option could be:
DefaultTableModel model = (DefaultTableModel) table.getModel();
Collections.shuffle(model.getDataVector());
model.fireTableDataChanged();
This cannot be reverted.