-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stopwatch
113 lines (90 loc) · 3.15 KB
/
Stopwatch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Stopwatch implements ActionListener {
JFrame frame = new JFrame();
JButton startButton = new JButton("START");
JButton resetButton = new JButton("RESET");
JLabel timeLabel = new JLabel();
int elapsedTime = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;
boolean started = false;
String seconds_string = String.format("%02d",seconds);
String minutes_string = String.format("%02d",minutes);
String hours_string = String.format("%02d",hours);
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
elapsedTime=elapsedTime+1000;
hours = (elapsedTime/3600000);
minutes = (elapsedTime/60000) % 60;
seconds = (elapsedTime/1000)% 60;
seconds_string = String.format("%02d",seconds);
minutes_string = String.format("%02d",minutes);
hours_string = String.format("%02d",hours);
timeLabel.setText(hours_string+":"+minutes_string+":"+seconds_string);
}
});
Stopwatch(){
timeLabel.setText(hours_string+":"+minutes_string+":"+seconds_string);
timeLabel.setBounds(100,100,200,100);
timeLabel.setFont(new Font("Verdana",Font.PLAIN,35));
timeLabel.setBorder(BorderFactory.createBevelBorder(1));
timeLabel.setOpaque(true);
timeLabel.setHorizontalAlignment(JTextField.CENTER);
startButton.setBounds(100,200,100,50);
startButton.setFont(new Font("Ink Free",Font.PLAIN,20));
startButton.setFocusable(false);
startButton.addActionListener(this);
resetButton.setBounds(200,200,100,50);
resetButton.setFont(new Font("Ink Free",Font.PLAIN,20));
resetButton.setFocusable(false);
resetButton.addActionListener(this);
frame.add(startButton);
frame.add(resetButton);
frame.add(timeLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450,450);
frame.setLayout(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==startButton) {
if(started==false) {
started = true;
startButton.setText("STOP");
start();
}
else {
started=false;
startButton.setText("START");
stop();
}
}
if (e.getSource()==resetButton) {
started=false;
startButton.setText("START");
reset();
}
}
void start() {
timer.start();
}
void stop() {
timer.stop();
}
void reset() {
timer.stop();
elapsedTime=0;
seconds=0;
minutes=0;
hours=0;
seconds_string = String.format("%02d",seconds);
minutes_string = String.format("%02d",minutes);
hours_string = String.format("%02d",hours);
timeLabel.setText(hours_string+":"+minutes_string+":"+seconds_string);
}
}