0

I have this simple GUI for a time registration application

gui

As the GUI is used for time registration, I'd like it to show a timer that runs as you press "Start" until you press "Stop".

Currently the two methods are done like this:

private void trStartBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
    trStartBtn.setEnabled(false);
    trStopBtn.setEnabled(true);

    startTime = System.nanoTime();
}                                          

private void trStopBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
    endTime = System.nanoTime();
    trStartBtn.setEnabled(true);
    trStopBtn.setEnabled(false);
    // Opgave Navn
    String taskName = JOptionPane.showInputDialog(
            this,
            "Task name",
            "Time Registration",
            JOptionPane.INFORMATION_MESSAGE);

    // Tiden det tog
    long result = endTime - startTime;
    double seconds = (double) result / 1000000000;
    int minutes = (int)seconds / 60;
    int hours = minutes / 60;
    String time = hours + ";" + minutes + ";" + (int) seconds;

    // Dags Dato
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Date today = new Date();
    String date = format.format(today);

    DefaultTableModel m = (DefaultTableModel)trTable.getModel();
    Object[] data = {date,time,taskName};
    m.addRow(data);
    trScrollPane.repaint();
}

But how would I add functionality so that the timer up to the right will tick every second as to show the time as you use the program? It's been a while and I am a bit rusty at Swing. I know that making a thread to take care of it is not safe.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
OmniOwl
  • 5,477
  • 17
  • 67
  • 116
  • See [this example](http://stackoverflow.com/a/21619240/2587435) or the one [below it](http://stackoverflow.com/a/21619465/2587435) using a `JLabel` – Paul Samsotha Apr 03 '14 at 01:50

1 Answers1

3

Use a Swing Timer to schedule the update of the label every second.

When you click the Start button you start the Timer and when you click the Stop button you stop the Timer.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Even though jtextfield.setText() doesn't need repaint/validation to work? – OmniOwl Apr 02 '14 at 23:10
  • @Vipar Swing components are smart enough to revalidate/repaint themselves when a property (like setText()) is invoked. Why are you using a JTextField. A text field is for entering text. I would think you only want to display text. – camickr Apr 02 '14 at 23:12
  • What else would I use to show the time as the timer is running? – OmniOwl Apr 02 '14 at 23:13