File: Clock.java

package info (click to toggle)
freetts 1.2.2-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 65,244 kB
  • sloc: java: 21,305; xml: 1,340; sh: 969; lisp: 587; ansic: 241; makefile: 25; awk: 11
file content (272 lines) | stat: -rw-r--r-- 7,856 bytes parent folder | download | duplicates (4)
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
/**
 * Copyright 2003 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and
 * redistribution of this file, and for a DISCLAIMER OF ALL
 * WARRANTIES.
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


/**
 * A talking clock powered by FreeTTS.
 */
public abstract class Clock extends JFrame {

    private JLabel timeLabel;
    private JCheckBox announceCheckBox;
    private JTextField intervalTextField;
    private int timeFontSize = 24;

    private GregorianCalendar calendar;
    private SimpleDateFormat dateFormat;

    private long lastSpeakTime;            // in milliseconds
    private int speakInterval = 300000;    // in milliseconds
    private int sleepTime = 5000;          // in milliseconds

    private static char announceMnemonic = 'A';
    private static char minutesMnemonic = 'M';
    private static char speakMnemonic = 'S';

    private boolean debug = true;
    

    /**
     * Constructs a default WebStartClock.
     */
    public Clock() {
        super("FreeTTS Clock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel timePanel = new JPanel(new BorderLayout());
        timePanel.setAlignmentY(JPanel.CENTER_ALIGNMENT);

        timeLabel = new JLabel("Loading...", JLabel.CENTER);
        Font oldFont = timeLabel.getFont();
        timeLabel.setFont(new Font(oldFont.getFontName(), oldFont.getStyle(),
                                   timeFontSize));

        timePanel.add(timeLabel, BorderLayout.CENTER);
        timePanel.add(createAnnouncePanel(), BorderLayout.SOUTH);
        
        getContentPane().add(timePanel, BorderLayout.CENTER);

        JButton speakButton = new JButton("Speak");
        speakButton.setMnemonic(speakMnemonic);

        speakButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                Runnable speaker = new Runnable() {
                    public void run() {
                        speakTime();
                    }
                };
                (new Thread(speaker)).start();
            }
        });

        getContentPane().add(speakButton, BorderLayout.SOUTH);
        
        createCalendar();
    }


    /**
     * Start running the clock.
     */
    public void startClock() {
        ClockThread clock = new ClockThread();
        clock.start();
    }


    /**
     * Creates the JPanel that allows you to specify the time announcing
     * interval.
     *
     * @return a JPanel
     */ 
    private JPanel createAnnouncePanel() {
        JPanel announcePanel = new JPanel(new FlowLayout());
        announceCheckBox = new JCheckBox("announce every", true);
        announceCheckBox.setMnemonic(announceMnemonic);
        announceCheckBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent ie) {
                if (ie.getStateChange() == ItemEvent.SELECTED) {
                    lastSpeakTime = calendar.getTimeInMillis();
                    debugPrintln
                        ("Last speak time: "  + String.valueOf(lastSpeakTime));
                }
            }
        });

        // a text field to enter the time announcing interval
        intervalTextField = new JTextField("5", 3);
        intervalTextField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String text = intervalTextField.getText();
                if (text.matches("[1-9][0-9]*")) {
                    debugPrintln("New announce interval : " + text);
                    speakInterval = Integer.parseInt(text) * 60000;
                } else {
                    debugPrintln("Invalid minutes input: " + text);
                    intervalTextField.setText
                        (String.valueOf(speakInterval / 60000));
                }
            }
        });

        JLabel minutesLabel = new JLabel("mins");
        minutesLabel.setDisplayedMnemonic(minutesMnemonic);
        minutesLabel.setLabelFor(intervalTextField);

        announcePanel.add(announceCheckBox);
        announcePanel.add(intervalTextField);
        announcePanel.add(minutesLabel);
        return announcePanel;
    }


    /**
     * Creates the synthesizer, called by the constructor.
     * Implement this method to create the appropriate synthesizer.
     * The created synthesizer will be used by the <code>speak()</code>
     * method, also to be implemented in the subclass.
     */
    public abstract void createSynthesizer();


    /**
     * Asks the synthesizer to speak the time given in full text.
     * Implement this method to call the appropriate method of the
     * created synthesizer to speak the given time.
     *
     * @param time the time given in full text
     */
    protected abstract void speak(String time);


    /**
     * Create the GregorianCalendar that keeps track of the time.
     */
    private void createCalendar() {
        calendar = new GregorianCalendar();

        // sets the format to display the current time
        // the format is "3:50 PM"
        dateFormat = new SimpleDateFormat("h:mm a");
        dateFormat.setCalendar(calendar);
    }


    /**
     * Sets the time label.
     *
     * @time time the time to set
     */
    private void setTimeLabel(final String time) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                timeLabel.setText(time);
            }
        });
    };


    /**
     * Updates the calendar and the display with the current time.
     */
    private void updateTime() {
        Date currentTime = new Date();
        calendar.setTime(currentTime);
        setTimeLabel(dateFormat.format(currentTime));
    }


    /**
     * Speaks the current time.
     */
    private void speakTime() {
        lastSpeakTime = calendar.getTimeInMillis();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);        

        if (hour < 0 || hour > 23) {
            throw new IllegalArgumentException("Bad time format: hour");
        }
        if (min < 0 || min > 59) {
            throw new IllegalArgumentException("Bad time format: min");
        }
        
        String theTime = TimeUtils.timeToString(hour, min);
        speak(theTime);
    }


    /**
     * Return true if we enough time has elapsed since the last announce
     * time.
     *
     * @return true its time to speak, false otherwise
     */
    private boolean isTimeToSpeak() {
        return ((lastSpeakTime + speakInterval) < calendar.getTimeInMillis());
    }


    /**
     * Print method for debug purposes.
     *
     * @param the debug message to print
     */
    private void debugPrintln(String line) {
        if (debug) {
            System.out.println(line);
        }
    }


    /**
     * A thread for the clock.
     */
    class ClockThread extends Thread {

        public void run() {
            while (true) {
                updateTime();
                if (announceCheckBox.isSelected() && isTimeToSpeak()) {
                    speakTime();
                }

                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }

    }
}