-1

I have a JTable with an AbstractTableModel containing data in a ArrayList. The list is only a few elements, but the properties of the objects changes rapidly (maybe 100 times per second)

I guess it will give bad performance to fire changes all the time.

Is it okay to use a timer to trigger JTable update every 1 second?

Timer timer = new Timer(1000, new ActionListener() {                
        @Override
        public void actionPerformed(ActionEvent e) {
            myModel.fireTableChanged(new TableModelEvent(myModel));
        }
    });
timer.start();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Stig
  • 1,974
  • 2
  • 23
  • 50
  • 1
    `TableChanged` is not a good idea, as it affects the current selection and column information, including renderers and editors. You should also not be calling the event triggers (`fireXxx`) from outside the models context, as it's not your responsibility. Instead, create a custom table with one or more update methods that trigger `tableRowsUpdated` instead for example. – MadProgrammer Dec 18 '14 at 21:03
  • Another solution might be to allow the model to actually do it's job and instead of reading the data directly from the changing `ArrayList`, which might cause race conditions between the `ArrayList` and the UI, use a `DefaultTableModel` and simply call `setValueAt` (or if empty, `addRow`), making sure you synchronise the updates between what ever is updating the `ArrayList` and the Event Dispatching Thread – MadProgrammer Dec 18 '14 at 21:04
  • It sounds cumbersome. In .net WPF and MVVM I could make a model with PropertyChanged events that would make the GUI update whenever another thread changes the model. This is fully thread safe. – Stig Dec 18 '14 at 21:34
  • Swing is not thread safe – MadProgrammer Dec 18 '14 at 22:14

1 Answers1

2

Use a SwingWorker. You can collect data in your implementation of doInBackground(), publish() interim results, and process() changes to the TableModel on the event dispatch thread at a sustainable rate. A complete example is seen here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045