Swing Shuffle JTable rows

by GarciaPL on Saturday 14 March 2015

Swing in my opinion is quite great framework or library whatever you prefer to create Java application on desktop. But after using it some time, I noticed that one of the disadvantage of Swing is that when you make some heavy calculation, that almost always your GUI is going to freeze. Of course you can not leave this in that way, so you must create some workaround. To make it happen you can use for instance Timer from javax.swing package of course.


        final Timer timer = new Timer(200, null);
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (isRandomizeRows()) {
                    ContestTableModel contest = getContestTableModel();
                    Vector data = contest.getData();
                    Collections.shuffle(data);
                    contest.setData(data);
                    getTablePlayers().setModel(contest);
                    getContestTableModel().fireTableDataChanged();
                }
            }
        };

As you can see method isRandomizeRows() only blocks execution of this Timer. I do not know why method .stop() which is implemented in this Timer simply does not work. Nevertheless there is a line where AbstractTableModel from our JTable is acquired (getContestTableModel()). After that you get data in Vector collection. Shuffle it's contents using Collections.shuffle(data) method. After that set data, set model and let to know JTable that it's data has changed.