Java JTable to be refreshed every 2 seconds

2019-03-04 00:18发布

问题:

Hy! I am working on java app that has 2 forms. In first form my user order meals and I store his order in my database on localhost server. On second form that orders in JTable by using simple sql query. Now I want to make that my JTable is refreshed every 2 seconds, so I can automatically see when user order meal. I tried with Timers, but I am total newbie in Java programming so I would appreciate help... Here is my method that refreshes table but I just need a bit help about Timer:

private void NapraviTablicu() {
    dohvatiNarudzbe(); //method for executing sql queries and filling my list KuhinjaListaJela with new ordered meals
    TableModel tableModel = new KitchenTableModel(KuhinjaListaJela);//Making new table model from list
    Tablica.setModel(tableModel);// displaying new meals in table
}

回答1:

A javax.swing.Timer is a little awkward for this; as is java.util.Timer. As long as you update your TableModel on the event dispatch thread, you can query the database on another thread every two seconds using either approach cited below. Note that it's OK to sleep on a background thread.

  • SwingWorker, seen here and here.

  • Runnable, seen here.