-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathButtonHAndler.java
88 lines (72 loc) · 2.21 KB
/
ButtonHAndler.java
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
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.*;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.lang.*;
public class ButtonHandler implements ActionListener {
private JButton iniciar, parar, resetar;
ScheduledFuture<?> result;
int counter = 0;
boolean isAlive = false;
public ButtonHandler(JButton iniciar, JButton parar, JButton resetar){
this.iniciar = iniciar;
this.parar = parar;
this.resetar = resetar;
}
public void actionPerformed(ActionEvent evento) {
if(evento.getSource() == iniciar) {
if (isAlive != true ) {
initCounter();
isAlive = true;
}
else {System.out.println("Ele já está rodando"); }
}
if (evento.getSource() == parar) {
if (isAlive == true) {
stopCounter();
isAlive = false;
}
}
if (evento.getSource() == resetar) {
if (isAlive == true) {
resetCounter();
}
else {
resetCounter2();
}
}
}
public void initCounter() {
Runnable runnable = new Runnable() {
@Override
public void run() {
incrementCounter();
System.out.println(counter);
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
result = service.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
}
public void stopCounter() {
result.cancel(true);
System.out.println("Contador parado em " + counter);
}
public void resetCounter() {
result.cancel(true);
System.out.println("Contador resetado em " + counter);
counter = 0;
initCounter();
}
public void resetCounter2() {
result.cancel(true);
System.out.println("Contador resetado em " + counter);
counter = 0;
}
public void incrementCounter() {
counter++;
}
}