0

How would a JTable update automatically based off of time? So every time the current time changes, the table updates automatically. Could some provide a snippet of code of how this may work in Java? To have the Table update after the time changes. Please and thank you in advance.

          package times;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class TableTimeChange {

DefaultTableModel model2 = new DefaultTableModel();

String rowdata[] = new String[8];
Date[] date123 = new Date[8];

private SimpleDateFormat format = new SimpleDateFormat("HH:mm:dd:ss");
private JTable table = new JTable(getTableModel());

public TableTimeChange() {
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    JFrame frame = new JFrame();
    frame.add(new JScrollPane(table));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();

    Timer timer = new Timer(1000, new TimerListener());
    timer.start();
    frame.setVisible(true);
}

private TableModel getTableModel() {
    String[] cols = {"Time"};


    String array1[] = { "12-12-2001 10:18:30 PM", "12-15-2001 10:18:54 PM"};
    String array2[] = {"01-19-1989 01:18:27 AM", "01-19-2019 01:28:36 PM"};
    String array3[] = {"12-05-1989 05:18:57 PM", "08-25-1989 09:18:27 PM"};
    String array4[] = { "10-15-1985 09:18:17 AM", "10-25-1985 06:48:27 AM"};
    String array5[] = {"06-10-2001 03:09:19 AM", "05-16-2011 03:29:10 AM"};
    String array6[] = {"01-12-2000 09:00:08 PM", "11-22-2010 07:00:56 PM"};
    String array7[] = { "07-19-1969 12:18:47 PM", "02-05-1969 01:18:17 AM"};
    String array8[] = {"01-09-2010 10:09:50 AM", "12-09-2010 05:09:10 PM"};


    rowdata[0] = array1[0];
    rowdata[1] = array2[0];
    rowdata[2] = array3[0];
    rowdata[3] = array4[0];
    rowdata[4] = array5[0];
    rowdata[5] = array6[0];
    rowdata[6] = array7[0];
    rowdata[7] = array8[0];


    for(int t = 0; t<rowdata.length; t++)
    {

        DateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
        DateFormat sdf3 = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");


        try {

            date123[t] = sdf.parse(rowdata[t]);


        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    for(int i = 0; i<8; i++)
    {



    String[][] data = {{getFormatDate(date123[i])},{ getFormatDate(date123[i])}};
    DefaultTableModel model = new DefaultTableModel(data, cols);

   model2 = model;


    }


    return model2;
}

private String getFormatDate(Date date) {
    return format.format(date);
}

private class TimerListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        for (int i = model.getRowCount() -1; i >= 0; i--) {
            model.setValueAt(getFormatDate(date123[i]), i, 0);
        }   
    }
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new TableTimeChange();
        }
    });
}
}
sayit
  • 15
  • 4
  • Do you mean like [this](http://stackoverflow.com/a/21355134/2587435)? – Paul Samsotha Aug 25 '14 at 14:00
  • very similar. So when I launched my GUI, the table should update as the time moves forward.... @peeskillet . Is that what the code is doing? – sayit Aug 25 '14 at 14:13
  • Yes, it is adding a new row every so many milliseconds. Use a Swing Timer for repeated events. See [How to Use Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for more details – Paul Samsotha Aug 25 '14 at 14:17
  • I don't want to add a new row. I want just the table to update/change when the time changes. @peeskillet Could you also provide a code snippet for this – sayit Aug 25 '14 at 14:25
  • 1
    What exactly do you want to update? It's unclear. I understand the table, but what you change about the table model/view that you need updated at a certain time, and not instantly? – Paul Samsotha Aug 25 '14 at 14:27
  • I want to view the data that is based off of the current time. So the table data is being updated every time the time changes @peeskillet – sayit Aug 25 '14 at 14:41

3 Answers3

3

Just use a Swing Timer, like I mention in the comment. You need to provide an ActionListener to the Timer, of which the actionPerformed will be called every so many milliseconds (whatever you provide as the first argument in the constructor). There you will update the table model with the new Date or formatted date (As I did in the example below), and change whatever data in the table based on that date.

See more at How to Use Swing Timers

Disclaimer: I'm so out of it. Why the heck did I use dd in the format? That should not be there. It should be "HH:mm:ss". I'm too lazy to change it.

enter image description here

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class TableTimeChange {

    private SimpleDateFormat format = new SimpleDateFormat("HH:mm:dd:ss");
    private JTable table = new JTable(getTableModel());

    public TableTimeChange() {
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(table));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();

        Timer timer = new Timer(1000, new TimerListener());
        timer.start();
        frame.setVisible(true);
    }

    private TableModel getTableModel() {
        String[] cols = {"Time", "Is Seconds Even"};
        Object[][] data = { { getNewRow() }, { getNewRow() } };
        DefaultTableModel model = new DefaultTableModel(data, cols);
        return model;
    }

    private String getFormatDate(Date date) {
        return format.format(date);
    }

    private Object[] getNewRow() {
        Calendar cal = Calendar.getInstance();
        int seconds = cal.get(Calendar.SECOND);
        boolean isSecondsEven = (seconds % 2 == 0);
        return new Object[] { getFormatDate(cal.getTime()), isSecondsEven };
    }

    private class TimerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            DefaultTableModel model = (DefaultTableModel)table.getModel();
            for (int i = model.getRowCount() -1; i >= 0; i--) {
                Object[] row = getNewRow();
                model.setValueAt(row[0], i, 0);
                model.setValueAt(row[1], i, 1);
            }   
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TableTimeChange();
            }
        });
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • No worries. I updated the answer with a new example. I think I misunderstood what you were trying to do. Instead of just updating the time, I update another value, based on the new time – Paul Samsotha Aug 25 '14 at 15:41
  • I have edited my code with your changes. As you can see, there are pre existing times in the rowdata array. As the time changes, I should only see the values that are near the current time in the table. It should show in the table. So every time the time changes, I should see different values every time. @peeskillet – sayit Aug 25 '14 at 16:02
  • Is there a question or are you just showing me how your implemented version? – Paul Samsotha Aug 25 '14 at 16:03
  • Well I am not getting what I want. My table is not updating with the values that corresponds to the time. I am asking how could I make this happen. @peeskillet – sayit Aug 25 '14 at 16:06
  • Sorry but I have no idea what you're trying to do with that code. Also what are you creating a new table model every iteration of that last loop? Makes no sense. – Paul Samsotha Aug 25 '14 at 16:10
  • All I am trying to do is have the table update with the values of rowdata base off of time. Thats all i am trying to do. I'm asking your help with this while using your code @peeskillet – sayit Aug 25 '14 at 16:12
  • You need to explain _exactly_ what is supposed to happen. The "value doesn't change" means nothing. You have made a bunch of changes and I have no idea what those changes are supposed to do – Paul Samsotha Aug 25 '14 at 16:18
  • Will do. Lets say you have an array with different pre existing times. Based off of the current time, the table should only show those times that goes with the current time. Can you change your code to fix this criteria. All I added was an array. As the time moves forward, the table should only show the times in the array that matches the current time. I hope this is better. @peeskillet – sayit Aug 25 '14 at 16:20
  • None of them will match the current time – Paul Samsotha Aug 25 '14 at 16:23
  • What if we set a time frame: 5 hours before the current time, and 7 hours after the current time @peeskillet – sayit Aug 25 '14 at 16:26
  • Look, honestly this is a fairly simple examples. You need to understand how tables and their models work. The timer is the simplest component. You know you that everything in the `actionPerformed` will occur every so many milliseconds, So do your stuff there, where you want to change the table values. All I do in my code is traverse the table model and set the values. Please take some time to read [How to use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) and [How to Use Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for more help. – Paul Samsotha Aug 25 '14 at 16:27
0

You can use Timer

import java.util.Timer;
...
Timer timer = new Timer();
timer.schedule(new TimerTask() 
{
  @Override
  public void run()
  {
    // Your code here
  }
}, time);
Jeremy
  • 105
  • 1
  • 4
  • 11
  • Don't use a util.Timer. Instead you should be using a Swing Timer (javax.swing.Timer) since all updates to Swing components should be done on the EDT. – camickr Aug 25 '14 at 14:48
0

THIS:

Timer timer = new Timer(500,new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent ae){
    if (a == true){
      System.out.println("Hello");
      a = false;
    }
    if (a == false){
      System.out.println("ByeBye");
      a = true;
    }
  }
}
boolean a = true;
public MyFrame(){
        initComponents();
        a = true;
        timer.start();
}
Vu Manh
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 03 '21 at 14:18