=> clean slate software_

An Alarm Clock in Java

The purpose of this project was to get my foot in the door with Java. And the result is the best damn alarm clock I’ve ever had! It is a simple program but a rock solid one. I have been using it for many months and it has not failed me once nor had any bug whatsoever. It has the only easy and fast alarm setting UI I have ever experienced (minutes can be incremented and decremented 1 or 10 at a time with single key presses). It also displays the date, and simple instructions for stopping or disabling the alarm (for those annoying occasions when someone else has to deal with it). Finally, it is hard coded to play a clip from the song “Wake up” by Korn. This has proven a great and effective way to start the morning!

Alarm.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*

The MIT License (MIT)

Copyright © 2021 Dean Lee

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

package alarm;

import java.lang.Error;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Clip;

/**
 *
 * @author dean
 */
public class Alarm extends javax.swing.JFrame implements ActionListener {

    private Audio audio = new Audio();
    private boolean audioPlaying = false;
    private boolean alarmEnabled = true;
    private Calendar previousTime = captureTime();
    private Calendar currentTime;
    private Calendar alarmTime = Calendar.getInstance();
        
    /**
     * Creates new form Alarm
     */
    public Alarm() {
        initComponents();
        initAlarm();
        initTimer();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        timeDisplay = new javax.swing.JLabel();
        message = new javax.swing.JLabel();
        alarmDisplay = new javax.swing.JLabel();
        dateDisplay = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Alarm");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        timeDisplay.setFont(new java.awt.Font("Dialog", 1, 48)); // NOI18N
        timeDisplay.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        timeDisplay.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        message.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        message.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        alarmDisplay.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N
        alarmDisplay.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        alarmDisplay.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        dateDisplay.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N
        dateDisplay.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        dateDisplay.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(183, 183, 183)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(alarmDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dateDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(timeDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(76, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(70, 70, 70)
                .addComponent(timeDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dateDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addComponent(alarmDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (audioPlaying)
            alarmOff();
        else
            handleSpecificKey(evt);    
    }//GEN-LAST:event_formKeyPressed

    private void handleSpecificKey(java.awt.event.KeyEvent evt) {
        switch(evt.getKeyCode()) {
            case KeyEvent.VK_PERIOD:
                alarmTime.roll(Calendar.HOUR_OF_DAY, 1);
                break;
            case KeyEvent.VK_COMMA:
                alarmTime.roll(Calendar.HOUR_OF_DAY, -1);
                break;
            case KeyEvent.VK_K:
                alarmTime.roll(Calendar.MINUTE, -1);
                break;
            case KeyEvent.VK_L:
                alarmTime.roll(Calendar.MINUTE, 1);
                break;
            case KeyEvent.VK_SEMICOLON:
                alarmTime.roll(Calendar.MINUTE, 10);
                break;
            case KeyEvent.VK_J:
                alarmTime.roll(Calendar.MINUTE, -10);
                break;
            case KeyEvent.VK_SLASH:
                alarmTime.set(Calendar.HOUR_OF_DAY, 12);
                break;
            case KeyEvent.VK_M:
                alarmTime.set(Calendar.HOUR_OF_DAY, 0);
                break;
            case KeyEvent.VK_SPACE:
                toggleAlarmEnabled();
                break;
        };
        updateAlarmDisplay();
    }
    
    // basically the "ticking" method.
    public void actionPerformed(ActionEvent e) {
        setTime();
        handleTimeChange();
        previousTime = currentTime;
    }
    
    private void alarmOff() {
        if (audioPlaying)
            audio.stop();
        audioPlaying = false;
        setAlarmMessage();
    }
    
    private void alarmOn() {
        if (!audioPlaying)
            audio.play();
        audioPlaying = true;
        message.setText("Press any key to stop audio.");
    }
    
    private void toggleAlarmEnabled() {
        if (alarmEnabled)
            alarmEnabled = false;
        else
            alarmEnabled = true;
        setAlarmMessage();
    }
    
    private void setAlarmMessage() {
        if (alarmEnabled)
            message.setText("Alarm enabled. Press space bar to disable.");
        else
            message.setText("Alarm disabled. Press space bar to enable.");
    }
    
    private void updateAlarmDisplay() {
        alarmDisplay.setText(String.format("%tR", alarmTime));
    }
    
    private Calendar captureTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        return cal;
    }
    
    private void setTime() {
        currentTime = captureTime();
        timeDisplay.setText(String.format("%tR", currentTime));
        dateDisplay.setText(String.format("%tD", currentTime));
    }
    
    private boolean timesMatch(Calendar timeA, Calendar timeB) {
        return (timeA.get(Calendar.HOUR_OF_DAY) == timeB.get(Calendar.HOUR_OF_DAY)) && (timeA.get(Calendar.MINUTE) == timeB.get(Calendar.MINUTE));
    }
    
    private boolean timeChanging() {
        return !timesMatch(previousTime, currentTime);
    }
    
    private boolean alarmMatching() {
        return timesMatch(currentTime, alarmTime);
    }
    
    private void handleAlarmMatch() {
        if (alarmEnabled && alarmMatching())
            alarmOn();
    }
    
    private void handleTimeChange() {
        if (timeChanging())
            handleAlarmMatch();
    }
    
    private void initAlarm() {
        alarmTime.set(Calendar.HOUR_OF_DAY, 0);
        alarmTime.set(Calendar.MINUTE, 0);
        updateAlarmDisplay();
        setAlarmMessage();
    }
    
    private void initTimer() {
        timer = new Timer(1000, this);
        timer.setInitialDelay(0);
        timer.start();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Alarm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Alarm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Alarm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Alarm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Alarm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel alarmDisplay;
    private javax.swing.JLabel dateDisplay;
    private javax.swing.JLabel message;
    private javax.swing.JLabel timeDisplay;
    // End of variables declaration//GEN-END:variables

    // Manually declared variables - can modify!
    private Timer timer;
}

class Audio {
    
    private Clip clip;
    
    public Audio() {
        init();
    }
    
    private void init() {
        try {
            File file = new File(
                getClass().getClassLoader().getResource("resources/wakeupkorn.wav").getFile()
            );
            AudioInputStream stream = AudioSystem.getAudioInputStream(file);
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip line = (Clip) AudioSystem.getLine(info);
            line.open(stream);
            line.setLoopPoints(0, -1);
            clip = line;
        }
        catch (Throwable e) {
            throw new Error(e.getMessage());
        }
    }
    
    public void play() {
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
    
    public void stop() {
        clip.stop();
        clip.setFramePosition(0);
    }
}