Stop watch button
What to do to operate the button to stop and start the clock, while I want it when pressed to stop and continue the count with changing of it's label.
Now I reached that the button start the count and change the label after that is doesn't work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ex1 extends JFrame implements Runnable {
int time = 0;
JLabel lb1 = new JLabel("Hours:");
JLabel lb2 = new JLabel("Minutes:");
JLabel lb3 = new JLabel("Seconds:");
JTextField hrs = new JTextField(10);
JTextField mts = new JTextField(10);
JTextField scd = new JTextField(10);
JPanel Lcontent = new JPanel();
Thread t = new Thread(this);
boolean flag = false;
JButton stp = new JButton("Start");
JFrame fr1 = new JFrame("Swing Window");
Container cp;
int mnts = 0;
int hors = 0;
public Ex1() {
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr1.setSize(700, 90);
fr1.setResizable(true);
cp = fr1.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(lb1);
cp.add(hrs);
cp.add(lb2);
cp.add(mts);
cp.add(lb3);
cp.add(scd);
cp.add(stp);
stp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (flag == false) {
stp.setText("Stop");
t.start();
}
flag = true;
//stp.setText("Start");
//t.stop();
}
});
fr1.show();
}
public void run() {
while (flag) {
try {
Thread.sleep(1000);
time++;
scd.setText("" + time);
if (time > 59) {
mnts++;
mts.setText("" + mnts);
time = 0;
}
if (mnts > 59) {
hors++;
hrs.setText("" + hors);
mnts = 0;
}
} 开发者_Go百科catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
new Ex1();
}
}
Updates to the properties of Swing components should be done on the EDT. The link from above provided by mre will provide more information on this. An easy way to make sure repeating code executes on the EDT is to use a Swing Timer.
See How to Use Swing Timers for more information.
精彩评论