Update table contents periodically

I want to refresh my table periodically since its contents change from time to time.

Please let me know what's the best way to do this. Thanks!
dshrenikAsked:
Who is Participating?
 
for_yanCommented:
Execute this (find some gif to add as before)
and look at the numbers - they will cahnge every
3 seconds.
If you see compiler warning, don't pay attenetion
it is not important.

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new BorderLayout());

    MyTableModel model = new MyTableModel();

    JTable table = new JTable(model);
    table.setRowHeight(80);
    table.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer());
    JScrollPane pane = new JScrollPane(table);
    frame.getContentPane().add(BorderLayout.CENTER, pane);
   // frame.setSize(500, 400);
      frame.pack();
    frame.setVisible(true);
      System.out.println("showed");

      try{
          while(true){
          Thread.currentThread().sleep(3000);
             model.toggleMult();
              frame.repaint();
          }

      }
          catch(Exception ex){

          }
      }

  }


class MyTableModel extends AbstractTableModel {
    boolean mult;

public void toggleMult(){
    mult = !mult;
}


  public Object getValueAt(int row, int column) {
      if(mult)
    return "" + (row * column);
      else return "" + (row + column);
  }

  public int getColumnCount() {
    return 4;
  }

  public int getRowCount() {
    return 5;
  }
}

class ImageRenderer extends DefaultTableCellRenderer {
  JLabel lbl = new JLabel();

  ImageIcon icon = new ImageIcon("HearthFlag.gif");

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    lbl.setText((String) value);
    lbl.setIcon(icon);
    return lbl;
  }
}

Open in new window

0
 
for_yanCommented:
You change table model contents and repaint your table
0
 
dshrenikAuthor Commented:
I am not changing the contents explicitly.

I want my program to poll data (from a server, for example). This must happen periodically, say eveery 20s. Should I have a timer, or is there a better way?
0
 
for_yanCommented:
while(true){
Thread.currentThread().sleep(20000);
//get new data and update the model
jtable.repaint();
}

0
 
dshrenikAuthor Commented:
This gets into the constructor?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.