0

I want a java program which displays time passed from the running of the program, a chronometer. First of all I created a Thread and variables called countSec, countMin and boolean stop. Eventually a String variable that holds the aforementioned values, then a JFrame and a JLabel are created, which will be used to display the String timeTimers on the JFrame. The thread sleeps 1000 milliseconds before becoming 1 value bigger, every 60 seconds countSec is set to zero and countMin is incremented by one.

Input:

class Timer implements Runnable {
    Thread thrd;
    private static int countSec = 0;
    private static int countMin = 0;
    private static boolean stop = false; // set to false to stop the program.
    String timeTimers = "sec: " + countSec + " min: " + countMin;
    
    JFrame jfrm;
    JLabel jlab;
    
    Timer() {
        
        jfrm = new JFrame("Timer In Java");
        
        jfrm.setSize(770, 440);
        
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        jfrm.setLayout(new FlowLayout());
        
        jlab = new JLabel();
        jlab.setText(timeTimers);
        
        jfrm.add(jlab);
                jfrm.setVisible(true);
        
    
    }
    
    
    public void run() {
        stop = false;
        try {
            do {
            countSec++;
            Thread.sleep(1000);
            
            
            
            if(countSec >= 60) {
                countSec = -1;
                countMin++;
            }
            
        } while(!stop);
            
    } catch(InterruptedException e) {}

    
    
    }
    
    

    
}
class TimerDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Timer();
            }
        });
        
        Timer t = new Timer();
        Thread a = new Thread(t);
        a.start();
         
         
         
    }

}

Desired output: A working chronometer that changes its seconds every second and its minutes changing every minute, implemented in a Swing program.

Output received: A chronometer whom label displays sec: 0 min: 0, but doesn't change at all its seconds.

Considerations: May be that the chronometer remains stopped because the Swing method can't see the Thread implementation

markspace
  • 10,621
  • 3
  • 25
  • 39
  • 1
    What is your question? You seem to have implemented everything. What's the problem? – NomadMaker Oct 29 '20 at 18:54
  • In run(), countMin in being incremented, but you're not modifying the minutes displayed in jlab. Also, using Thread.sleep on the main gui thread causes your entire gui to pause. – NomadMaker Oct 29 '20 at 18:58
  • 1
    I'm sure if you googled "java swing timer" you'd get better results, but I would start by creating a thread (like you have). I would create this outside of swing. When you need to change the label, I would use SwingUtilities.invokeLater() to change the label. – NomadMaker Oct 29 '20 at 19:00
  • @Abra I would expect a simple web search for something as common as this. A simple line in the question, "I searched on these terms and found nothing I could understand" would be enough. However, this is a common question here; there is almost one each day. – NomadMaker Oct 29 '20 at 19:19

2 Answers2

1

Here's my version of the same thing. Note I use a java.swing.Timer and that I update a Swing component, not just a variable.

This is very quick and dirty code, caveat emptor. Just something I did basically on the fly.

        timing = true;
        timer = new javax.swing.Timer( 1000,
                new ActionListener()
                {
                   @Override
                   public void actionPerformed( ActionEvent e )
                   {
                      long minuteTime = ( System.nanoTime() -
                      nanoTime ) /
                      ( 60_000_000_000L );
                      view.setTimerLabel( minuteTime + " minutes" );
                      if( minuteTime > sitTime )
                         if( darkBg ) {
                            view.setBackground( Color.PINK );
                            darkBg = false;
                         } else {
                            view.setBackground( Color.PINK.
                                    darker() );
                            darkBg = true;
                         }
                   }
                } );
        timer.setRepeats( true );
        timer.start();
     }
  }
markspace
  • 10,621
  • 3
  • 25
  • 39
0

this is a simple example using java.util.Timer :

package test;

import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

    Timer t;
    private int sec = 0;
    private boolean stop = true; // set to false to stop the program.
    JLabel lab;
    JButton startBtn;
    JButton stopBtn;

    Test() {
        super("Timer In Java");
        this.setSize(770, 440);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());
        lab = new JLabel();
        startBtn = new JButton("start");
        startBtn.addActionListener((e)->{
            stop = false;
        });
        stopBtn = new JButton("stop");
        stopBtn.addActionListener((e)->{
            stop = true;
        });
        lab.setText("sec : 0 , min : 0");
        this.add(lab);
        this.add(startBtn);
        this.add(stopBtn);
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b); 
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                if(!stop){
                    sec++;
                SwingUtilities.invokeLater(()->{
                    lab.setText("sec : "+(sec%60)+" , min : "+(sec/60)); 
                });
                }
            }
        }
        , 0, 1000);
    }
    
    

    public static void main(String[] args) {
        Test t = new Test();
        t.setVisible(true);
    }
}

enter image description here

aziz k'h
  • 775
  • 6
  • 11