java Swing Stop Watch
java swing frame work is a great frame work when it comes to develop cross-platform software development.swing is actually a UI component library which support java platform.first came out bundled with Net-Beans IDE.which is a great Dev-environment for a some time and still to today.
today i'm going to develop a java swing stop watch.which involves java Thread class so this software will be a multi threaded application.
global variables and objects :
private Thread TMR;
private byte MIN = 0;
private byte SEC = 0;
private byte MSEC = 0;
private volatile boolean RUNNING = true;
private volatile boolean PAUSED = false;
private Object PAUSELOCK = new Object();
timer start method :
private void start_timer() {
if (!jButton1.isEnabled()) {
return;
}
jButton2.setEnabled(true);
jButton3.setEnabled(true);
reset_all();
TMR = new Thread(() -> {
jButton1.setEnabled(false);
while (RUNNING) {
synchronized (PAUSELOCK) {
if (!RUNNING) {
break;
}
if (PAUSED) {
try {
PAUSELOCK.wait();
} catch (InterruptedException ex) {
break;
}
if (!RUNNING) {
break;
}
}
}
MSEC++;
if (MSEC == 100) {
jLabel5.setText(String.format("%02d", 0));
} else {
jLabel5.setText(String.format("%02d", MSEC));
}
if (MSEC >= 100) {
MSEC = 0;
SEC++;
if (SEC == 60) {
jLabel2.setText(String.format("%02d", 0));
} else {
jLabel2.setText(String.format("%02d", SEC));
}
if (SEC >= 60) {
SEC = 0;
MIN++;
if (MIN == 60) {
jLabel1.setText(String.format("%02d", 0));
} else {
jLabel1.setText(String.format("%02d", MIN));
}
if (MIN >= 60) {
MSEC = 0;
SEC = 0;
MIN = 0;
}
}
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
});
TMR.start();
}
timer pause method:
public void pause_timer() {
PAUSED = true;
}
timer resume method:
public void resume_timer() {
synchronized (PAUSELOCK) {
PAUSED = false;
PAUSELOCK.notify();
}
}
reset method:
public void reset_all() {
MSEC = 0;
SEC = 0;
MIN = 0;
jLabel1.setText(String.format("%02d", 0));
jLabel2.setText(String.format("%02d", 0));
jLabel5.setText(String.format("%02d", 0));
RUNNING = true;
PAUSED = false;
PAUSELOCK = new Object();
}
timer stop method:
public void stop_timer() {
RUNNING = false;
TMR.interrupt();
reset_all();
jButton1.setEnabled(true);
}
download net beans project files :
github