KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > joda > example > time > AgeCalculator


1 /*
2  * Copyright 2001-2005 Stephen Colebourne
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.joda.example.time;
17
18 import java.awt.Component JavaDoc;
19 import java.awt.Container JavaDoc;
20 import java.awt.Dimension JavaDoc;
21 import java.awt.GridBagConstraints JavaDoc;
22 import java.awt.GridBagLayout JavaDoc;
23 import java.awt.event.ActionEvent JavaDoc;
24 import java.awt.event.ActionListener JavaDoc;
25 import java.awt.event.ItemEvent JavaDoc;
26 import java.awt.event.ItemListener JavaDoc;
27
28 import javax.swing.BorderFactory JavaDoc;
29 import javax.swing.Box JavaDoc;
30 import javax.swing.BoxLayout JavaDoc;
31 import javax.swing.JCheckBox JavaDoc;
32 import javax.swing.JComboBox JavaDoc;
33 import javax.swing.JComponent JavaDoc;
34 import javax.swing.JFrame JavaDoc;
35 import javax.swing.JLabel JavaDoc;
36 import javax.swing.JPanel JavaDoc;
37 import javax.swing.JTextField JavaDoc;
38 import javax.swing.Timer JavaDoc;
39 import javax.swing.event.DocumentEvent JavaDoc;
40 import javax.swing.event.DocumentListener JavaDoc;
41 import javax.swing.text.Document JavaDoc;
42
43 import org.joda.time.Chronology;
44 import org.joda.time.DateTime;
45 import org.joda.time.DateTimeZone;
46 import org.joda.time.DurationField;
47 import org.joda.time.chrono.ISOChronology;
48
49 /**
50  * AgeCalculator is a small Swing application that computes age from a specific
51  * birthdate and time zone. Age is broken down into multiple fields, which can
52  * be independently disabled.
53  *
54  * @author Brian S O'Neill
55  */

56 public class AgeCalculator extends JFrame JavaDoc {
57     static final int
58         YEARS = 1,
59         MONTHS = 2,
60         DAYS = 3,
61         WEEKYEARS = 4,
62         WEEKS = 5,
63         HOURS = 101,
64         MINUTES = 102,
65         SECONDS = 103;
66
67     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
68         new AgeCalculator().show();
69     }
70
71     static JComponent JavaDoc fixedSize(JComponent JavaDoc component) {
72         component.setMaximumSize(component.getPreferredSize());
73         return component;
74     }
75
76     static JComponent JavaDoc fixedHeight(JComponent JavaDoc component) {
77         Dimension JavaDoc dim = component.getMaximumSize();
78         dim.height = component.getPreferredSize().height;
79         component.setMaximumSize(dim);
80         return component;
81     }
82
83     Chronology iChronology;
84
85     private String JavaDoc iBirthdateStr;
86     private FieldSet[] iFieldSets;
87     private Timer JavaDoc iTimer;
88
89     public AgeCalculator() {
90         super();
91
92         iChronology = ISOChronology.getInstance();
93         iBirthdateStr = "1970-01-01T00:00:00";
94
95         setTitle("Age Calculator");
96         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
97         addMainArea(getContentPane());
98         addNotify();
99         Dimension JavaDoc size = getPreferredSize();
100         setSize(size);
101         Dimension JavaDoc screenSize = getToolkit().getScreenSize();
102         setLocation(screenSize.width / 2 - size.width / 2,
103                     screenSize.height / 2 - size.height / 2);
104
105         iTimer = new Timer JavaDoc(500, new ActionListener JavaDoc() {
106             public void actionPerformed(ActionEvent JavaDoc e) {
107                 updateResults();
108             }
109         });
110
111         iTimer.setInitialDelay(0);
112         iTimer.start();
113     }
114
115     private void addMainArea(Container JavaDoc container) {
116         JPanel JavaDoc panel = new JPanel JavaDoc();
117         panel.setLayout(new BoxLayout JavaDoc(panel, BoxLayout.Y_AXIS));
118
119         addTopArea(panel);
120         panel.add(Box.createVerticalStrut(10));
121         addBottomArea(panel);
122         panel.add(Box.createVerticalGlue());
123
124         panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
125
126         container.add(panel);
127     }
128
129     private void addTopArea(Container JavaDoc container) {
130         JPanel JavaDoc panel = new JPanel JavaDoc();
131         panel.setLayout(new BoxLayout JavaDoc(panel, BoxLayout.X_AXIS));
132
133         panel.add(fixedHeight(new JLabel JavaDoc("Birthdate")));
134         panel.add(Box.createHorizontalStrut(10));
135
136         final JTextField JavaDoc birthdateField = new JTextField JavaDoc(iBirthdateStr + ' ');
137         Document JavaDoc doc = birthdateField.getDocument();
138         doc.addDocumentListener(new DocumentListener JavaDoc() {
139             public void insertUpdate(DocumentEvent JavaDoc e) {
140                 update(e);
141             }
142             public void removeUpdate(DocumentEvent JavaDoc e) {
143                 update(e);
144             }
145             public void changedUpdate(DocumentEvent JavaDoc e) {
146                 update(e);
147             }
148             private void update(DocumentEvent JavaDoc e) {
149                 iBirthdateStr = birthdateField.getText();
150                 updateResults();
151             }
152         });
153         panel.add(fixedHeight(birthdateField));
154
155         panel.add(Box.createHorizontalStrut(10));
156
157         Object JavaDoc[] ids = DateTimeZone.getAvailableIDs().toArray();
158         final JComboBox JavaDoc zoneSelector = new JComboBox JavaDoc(ids);
159         zoneSelector.setSelectedItem(DateTimeZone.getDefault().getID());
160         panel.add(fixedSize(zoneSelector));
161
162         zoneSelector.addActionListener(new ActionListener JavaDoc() {
163             public void actionPerformed(ActionEvent JavaDoc e) {
164                 String JavaDoc id = (String JavaDoc)zoneSelector.getSelectedItem();
165                 iChronology = ISOChronology.getInstance(DateTimeZone.forID(id));
166                 updateResults();
167             }
168         });
169
170         container.add(fixedHeight(panel));
171     }
172
173     private void addBottomArea(Container JavaDoc container) {
174         JPanel JavaDoc panel = new JPanel JavaDoc();
175         panel.setLayout(new BoxLayout JavaDoc(panel, BoxLayout.X_AXIS));
176
177         ItemListener JavaDoc listener = new ItemListener JavaDoc() {
178             public void itemStateChanged(ItemEvent JavaDoc e) {
179                 updateResults();
180             }
181         };
182
183         iFieldSets = new FieldSet[] {
184             new FieldSet("Month Based", new FieldGroup[] {
185                 new FieldGroup(listener, "Years", YEARS),
186                 new FieldGroup(listener, "Months", MONTHS),
187                 new FieldGroup(listener, "Days", DAYS),
188                 new FieldGroup(listener, "Hours", HOURS),
189                 new FieldGroup(listener, "Minutes", MINUTES),
190                 new FieldGroup(listener, "Seconds", SECONDS)
191             })
192             ,
193             new FieldSet("Week Based", new FieldGroup[] {
194                 new FieldGroup(listener, "Weekyears", WEEKYEARS),
195                 new FieldGroup(listener, "Weeks", WEEKS),
196                 new FieldGroup(listener, "Days", DAYS),
197                 new FieldGroup(listener, "Hours", HOURS),
198                 new FieldGroup(listener, "Minutes", MINUTES),
199                 new FieldGroup(listener, "Seconds", SECONDS)
200             })
201         };
202
203         for (int i=0; i<iFieldSets.length; i++) {
204             if (i > 0) {
205                 panel.add(Box.createHorizontalStrut(10));
206             }
207             iFieldSets[i].addTo(panel);
208         }
209         panel.add(Box.createVerticalGlue());
210
211         container.add(fixedHeight(panel));
212     }
213
214     private void updateResults() {
215         try {
216             DateTime dt = new DateTime(iBirthdateStr.trim(), iChronology);
217
218             long minuend = System.currentTimeMillis();
219             long subtrahend = dt.getMillis();
220
221             for (int i=0; i<iFieldSets.length; i++) {
222                 iFieldSets[i].updateResults(minuend, subtrahend);
223             }
224         }
225         catch (IllegalArgumentException JavaDoc e) {
226             for (int i=0; i<iFieldSets.length; i++) {
227                 iFieldSets[i].setResultsText("");
228             }
229         }
230     }
231
232     private class FieldGroup {
233         public final JCheckBox JavaDoc iCheckbox;
234         public final JTextField JavaDoc iResult;
235         public final int iFieldType;
236
237         FieldGroup(ItemListener JavaDoc listener, String JavaDoc checkboxText, int fieldType) {
238             iCheckbox = new JCheckBox JavaDoc(checkboxText, true);
239             iCheckbox.addItemListener(listener);
240             iResult = new JTextField JavaDoc();
241             iResult.setEditable(false);
242             iFieldType = fieldType;
243         }
244
245         public long updateResult(long minuend, long subtrahend) {
246             // Because time zone can be dynamically changed, field must be
247
// dynamically acquired.
248

249             DurationField field;
250             switch (iFieldType) {
251             case YEARS:
252                 field = iChronology.years();
253                 break;
254             case MONTHS:
255                 field = iChronology.months();
256                 break;
257             case DAYS:
258                 field = iChronology.days();
259                 break;
260             case WEEKYEARS:
261                 field = iChronology.weekyears();
262                 break;
263             case WEEKS:
264                 field = iChronology.weeks();
265                 break;
266             case HOURS:
267                 field = iChronology.hours();
268                 break;
269             case MINUTES:
270                 field = iChronology.minutes();
271                 break;
272             case SECONDS: default:
273                 field = iChronology.seconds();
274                 break;
275             }
276
277             String JavaDoc textToSet = "";
278
279             if (iCheckbox.isSelected()) {
280                 long difference = field.getDifferenceAsLong(minuend, subtrahend);
281                 textToSet = Long.toString(difference);
282                 subtrahend = field.add(subtrahend, difference);
283             }
284
285             if (!iResult.getText().equals(textToSet)) {
286                 iResult.setText(textToSet);
287             }
288
289             return subtrahend;
290         }
291
292         public void setResultText(String JavaDoc text) {
293             iResult.setText(text);
294         }
295     }
296
297     private static class FieldSet {
298         private final String JavaDoc iTitle;
299         private final FieldGroup[] iGroups;
300
301         FieldSet(String JavaDoc title, FieldGroup[] groups) {
302             iTitle = title;
303             iGroups = groups;
304         }
305
306         private long updateResults(long minuend, long subtrahend) {
307             for (int i=0; i<iGroups.length; i++) {
308                 subtrahend = iGroups[i].updateResult(minuend, subtrahend);
309             }
310             return subtrahend;
311         }
312
313         public void setResultsText(String JavaDoc text) {
314             for (int i=0; i<iGroups.length; i++) {
315                 iGroups[i].setResultText(text);
316             }
317         }
318
319         private void addTo(Container JavaDoc container) {
320             JPanel JavaDoc panel = new JPanel JavaDoc();
321             GridBagLayout JavaDoc layout = new GridBagLayout JavaDoc();
322             panel.setLayout(layout);
323
324             panel.setBorder(BorderFactory.createTitledBorder(iTitle));
325
326             for (int i=0; i<iGroups.length; i++) {
327                 FieldGroup fg = iGroups[i];
328                 panel.add(fg.iCheckbox);
329                 setCheckboxConstraints(layout, fg.iCheckbox, 0, i);
330                 panel.add(fg.iResult);
331                 setResultConstraints(layout, fg.iResult, 1, i);
332             }
333
334             container.add(fixedHeight(panel));
335         }
336
337         private void setCheckboxConstraints(GridBagLayout JavaDoc layout, Component JavaDoc c,
338                                             int x, int y)
339         {
340             GridBagConstraints JavaDoc cons = new GridBagConstraints JavaDoc();
341             cons.gridx = x;
342             cons.gridy = y;
343             cons.weightx = 0.1;
344             cons.anchor = GridBagConstraints.WEST;
345             layout.setConstraints(c, cons);
346         }
347
348         private void setResultConstraints(GridBagLayout JavaDoc layout, Component JavaDoc c,
349                                           int x, int y)
350         {
351             GridBagConstraints JavaDoc cons = new GridBagConstraints JavaDoc();
352             cons.gridx = x;
353             cons.gridy = y;
354             cons.weightx = 1.0;
355             cons.anchor = GridBagConstraints.WEST;
356             cons.fill = GridBagConstraints.HORIZONTAL;
357             layout.setConstraints(c, cons);
358         }
359     }
360 }
361
Popular Tags