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