-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenTimeMonitor.java
More file actions
89 lines (76 loc) · 2.98 KB
/
ScreenTimeMonitor.java
File metadata and controls
89 lines (76 loc) · 2.98 KB
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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.time.*;
import java.util.Timer;
import java.util.TimerTask;
public class ScreenTimeMonitor extends JFrame {
private JLabel timeLabel;
private JTextField limitField;
private JButton setLimitButton;
private int screenTimeSeconds = 0;
private int limitSeconds = 0;
private Timer timer;
public ScreenTimeMonitor() {
setTitle("Screen Time Monitor");
setSize(350, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel("Screen Time: 00:00:00");
limitField = new JTextField(5);
setLimitButton = new JButton("Set Limit (min)");
add(timeLabel);
add(limitField);
add(setLimitButton);
setLimitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int minutes = Integer.parseInt(limitField.getText());
limitSeconds = minutes * 60;
JOptionPane.showMessageDialog(null, "Limit set to " + minutes + " minutes");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
}
}
});
startTracking();
setVisible(true);
}
private void startTracking() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
screenTimeSeconds++;
String formattedTime = formatTime(screenTimeSeconds);
timeLabel.setText("Screen Time: " + formattedTime);
if (limitSeconds > 0 && screenTimeSeconds >= limitSeconds) {
JOptionPane.showMessageDialog(null, "Time limit reached!", "Alert", JOptionPane.WARNING_MESSAGE);
limitSeconds = 0;
}
if (screenTimeSeconds % 60 == 0) {
saveLog();
}
}
}, 1000, 1000);
}
private String formatTime(int totalSeconds) {
int hours = totalSeconds / 3600;
int minutes = (totalSeconds % 3600) / 60;
int seconds = totalSeconds % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
private void saveLog() {
String fileName = "screen_time_log.txt";
String today = LocalDate.now().toString();
String entry = today + " - Total: " + formatTime(screenTimeSeconds) + "\n";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(entry);
} catch (IOException e) {
System.out.println("Error saving log: " + e.getMessage());
}
}
public static void main(String[] args) {
new ScreenTimeMonitor();
}
}