KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hero > client > grapheditor > DateComboBox


1 package hero.client.grapheditor;
2
3
4 import java.awt.*;
5 import java.awt.event.*;
6 import java.util.Calendar JavaDoc;
7 import java.text.SimpleDateFormat JavaDoc;
8
9 import javax.swing.*;
10 import javax.swing.event.PopupMenuListener JavaDoc;
11 import javax.swing.event.PopupMenuEvent JavaDoc;
12 import javax.swing.plaf.ComboBoxUI JavaDoc;
13 import javax.swing.plaf.basic.ComboPopup JavaDoc;
14 import javax.swing.plaf.metal.MetalComboBoxUI JavaDoc;
15 import javax.swing.border.Border JavaDoc;
16 import javax.swing.border.EtchedBorder JavaDoc;
17 import javax.swing.border.EmptyBorder JavaDoc;
18
19 import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
20 import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;
21
22 /**
23  * @version 1.0 11/02/2000
24  */

25
26 //////////////////////////////////////////////////////////////
27

28 public class DateComboBox extends JComboBox {
29
30 static java.util.ResourceBundle JavaDoc resource = java.util.ResourceBundle.getBundle("resources.Traduction")/*#BundleType=List*/;
31
32     protected SimpleDateFormat JavaDoc dateFormat = new SimpleDateFormat JavaDoc("MMM d, yyyy");
33     public void setDateFormat(SimpleDateFormat JavaDoc dateFormat) {
34     this.dateFormat = dateFormat;
35     }
36     public void setSelectedItem(Object JavaDoc item) {
37     // Could put extra logic here or in renderer when item is instanceof Date, Calendar, or String
38
// Dont keep a list ... just the currently selected item
39
removeAllItems(); // hides the popup if visible
40
addItem(item);
41     super.setSelectedItem(item);
42     }
43
44     public void updateUI() {
45     ComboBoxUI JavaDoc cui = (ComboBoxUI JavaDoc) UIManager.getUI(this);
46     if (cui instanceof MetalComboBoxUI JavaDoc) {
47         cui = new MetalDateComboBoxUI();
48     } else if (cui instanceof MotifComboBoxUI) {
49         cui = new MotifDateComboBoxUI();
50     } else if (cui instanceof WindowsComboBoxUI) {
51         cui = new WindowsDateComboBoxUI();
52     }
53         setUI(cui);
54     }
55
56     // Inner classes are used purely to keep DateComboBox component in one file
57
//////////////////////////////////////////////////////////////
58
// UI Inner classes -- one for each supported Look and Feel
59
//////////////////////////////////////////////////////////////
60

61     class MetalDateComboBoxUI extends MetalComboBoxUI JavaDoc {
62     protected ComboPopup JavaDoc createPopup() {
63         return new DatePopup( comboBox );
64     }
65     }
66
67     class WindowsDateComboBoxUI extends WindowsComboBoxUI {
68     protected ComboPopup JavaDoc createPopup() {
69         return new DatePopup( comboBox );
70     }
71     }
72
73     class MotifDateComboBoxUI extends MotifComboBoxUI {
74     protected ComboPopup JavaDoc createPopup() {
75         return new DatePopup( comboBox );
76     }
77     }
78
79     //////////////////////////////////////////////////////////////
80
// DatePopup inner class
81
//////////////////////////////////////////////////////////////
82

83     class DatePopup implements ComboPopup JavaDoc, MouseMotionListener,
84                    MouseListener, KeyListener, PopupMenuListener JavaDoc {
85     
86     protected JComboBox comboBox;
87     protected Calendar JavaDoc calendar;
88     protected JPopupMenu popup;
89     protected JLabel monthLabel;
90     protected JPanel days = null;
91     protected SimpleDateFormat JavaDoc monthFormat = new SimpleDateFormat JavaDoc("MMM yyyy");
92
93     protected Color selectedBackground;
94     protected Color selectedForeground;
95     protected Color background;
96     protected Color foreground;
97
98     public DatePopup(JComboBox comboBox) {
99         this.comboBox = comboBox;
100         calendar = Calendar.getInstance();
101         // check Look and Feel
102
background = UIManager.getColor("ComboBox.background");
103         foreground = UIManager.getColor("ComboBox.foreground");
104         selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
105         selectedForeground = UIManager.getColor("ComboBox.selectionForeground");
106
107         initializePopup();
108     }
109
110     //========================================
111
// begin ComboPopup method implementations
112
//
113
public void show() {
114         try {
115         // if setSelectedItem() was called with a valid date, adjust the calendar
116
calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
117         } catch (Exception JavaDoc e) {}
118         updatePopup();
119         popup.show(comboBox, 0, comboBox.getHeight());
120         }
121     
122     public void hide() {
123         popup.setVisible(false);
124     }
125
126     protected JList list = new JList();
127     public JList getList() {
128         return list;
129     }
130
131     public MouseListener getMouseListener() {
132         return this;
133     }
134
135     public MouseMotionListener getMouseMotionListener() {
136         return this;
137     }
138
139     public KeyListener getKeyListener() {
140         return this;
141     }
142
143     public boolean isVisible() {
144         return popup.isVisible();
145     }
146     
147     public void uninstallingUI() {
148         popup.removePopupMenuListener(this);
149     }
150
151     //
152
// end ComboPopup method implementations
153
//======================================
154

155
156
157     //===================================================================
158
// begin Event Listeners
159
//
160

161     // MouseListener
162

163     public void mousePressed( MouseEvent e ) {}
164         public void mouseReleased( MouseEvent e ) {}
165     // something else registered for MousePressed
166
public void mouseClicked(MouseEvent e) {
167             if ( !SwingUtilities.isLeftMouseButton(e) )
168                 return;
169             if ( !comboBox.isEnabled() )
170                 return;
171         if ( comboBox.isEditable() ) {
172         comboBox.getEditor().getEditorComponent().requestFocus();
173         } else {
174         comboBox.requestFocus();
175         }
176         togglePopup();
177     }
178
179     protected boolean mouseInside = false;
180     public void mouseEntered(MouseEvent e) {
181         mouseInside = true;
182     }
183     public void mouseExited(MouseEvent e) {
184         mouseInside = false;
185     }
186
187     // MouseMotionListener
188
public void mouseDragged(MouseEvent e) {}
189     public void mouseMoved(MouseEvent e) {}
190            
191     // KeyListener
192
public void keyPressed(KeyEvent e) {}
193     public void keyTyped(KeyEvent e) {}
194     public void keyReleased( KeyEvent e ) {
195         if ( e.getKeyCode() == KeyEvent.VK_SPACE ||
196          e.getKeyCode() == KeyEvent.VK_ENTER ) {
197         togglePopup();
198         }
199     }
200
201     /**
202      * Variables hideNext and mouseInside are used to
203      * hide the popupMenu by clicking the mouse in the JComboBox
204      */

205     public void popupMenuCanceled(PopupMenuEvent JavaDoc e) {}
206     protected boolean hideNext = false;
207     public void popupMenuWillBecomeInvisible(PopupMenuEvent JavaDoc e) {
208         hideNext = mouseInside;
209     }
210     public void popupMenuWillBecomeVisible(PopupMenuEvent JavaDoc e) {}
211            
212     //
213
// end Event Listeners
214
//=================================================================
215

216     //===================================================================
217
// begin Utility methods
218
//
219

220     protected void togglePopup() {
221         if ( isVisible() || hideNext ) {
222         hide();
223         } else {
224         show();
225         }
226         hideNext = false;
227     }
228
229     //
230
// end Utility methods
231
//=================================================================
232

233     // Note *** did not use JButton because Popup closes when pressed
234
protected JLabel createUpdateButton(final int field, final int amount) {
235         final JLabel label = new JLabel();
236         final Border JavaDoc selectedBorder = new EtchedBorder JavaDoc();
237         final Border JavaDoc unselectedBorder = new EmptyBorder JavaDoc(selectedBorder.getBorderInsets(new JLabel()));
238         label.setBorder(unselectedBorder);
239         label.setForeground(foreground);
240         label.addMouseListener(new MouseAdapter() {
241             public void mouseReleased(MouseEvent e) {
242             calendar.add(field, amount);
243             updatePopup();
244             }
245             public void mouseEntered(MouseEvent e) {
246             label.setBorder(selectedBorder);
247             }
248             public void mouseExited(MouseEvent e) {
249             label.setBorder(unselectedBorder);
250             }
251         });
252         return label;
253     }
254
255
256     protected void initializePopup() {
257         JPanel header = new JPanel(); // used Box, but it wasn't Opaque
258
header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
259         header.setBackground(background);
260         header.setOpaque(true);
261
262         JLabel label;
263         label = createUpdateButton(Calendar.YEAR, -1);
264         label.setText("<<");
265         label.setToolTipText(resource.getString("datecombobox.prevyear"));
266
267         header.add(Box.createHorizontalStrut(12));
268         header.add(label);
269         header.add(Box.createHorizontalStrut(12));
270
271         label = createUpdateButton(Calendar.MONTH, -1);
272         label.setText("<");
273         label.setToolTipText(resource.getString("datecombobox.prevmonth"));
274         header.add(label);
275
276         monthLabel = new JLabel("", JLabel.CENTER);
277         monthLabel.setForeground(foreground);
278         header.add(Box.createHorizontalGlue());
279         header.add(monthLabel);
280         header.add(Box.createHorizontalGlue());
281
282         label = createUpdateButton(Calendar.MONTH, 1);
283         label.setText(">");
284         label.setToolTipText(resource.getString("datecombobox.nextmonth"));
285         header.add(label);
286
287         label = createUpdateButton(Calendar.YEAR, 1);
288         label.setText(">>");
289         label.setToolTipText(resource.getString("datecombobox.nextyear"));
290
291         header.add(Box.createHorizontalStrut(12));
292         header.add(label);
293         header.add(Box.createHorizontalStrut(12));
294
295         popup = new JPopupMenu();
296         popup.setBorder(BorderFactory.createLineBorder(Color.black));
297         popup.setLayout(new BorderLayout());
298         popup.setBackground(background);
299         popup.addPopupMenuListener(this);
300         popup.add(BorderLayout.NORTH, header);
301     }
302
303     // update the Popup when either the month or the year of the calendar has been changed
304
protected void updatePopup() {
305         monthLabel.setText( monthFormat.format(calendar.getTime()) );
306         if (days != null) {
307         popup.remove(days);
308         }
309         days = new JPanel(new GridLayout(0, 7));
310         days.setBackground(background);
311         days.setOpaque(true);
312
313         Calendar JavaDoc setupCalendar = (Calendar JavaDoc) calendar.clone();
314         setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
315         for (int i = 0; i < 7; i++) {
316         int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
317         JLabel label = new JLabel();
318         label.setHorizontalAlignment(JLabel.CENTER);
319         label.setForeground(foreground);
320         if (dayInt == Calendar.SUNDAY) {
321             label.setText(resource.getString("datecombobox.sun"));
322         } else if (dayInt == Calendar.MONDAY) {
323             label.setText(resource.getString("datecombobox.mon"));
324         } else if (dayInt == Calendar.TUESDAY) {
325             label.setText(resource.getString("datecombobox.tue"));
326         } else if (dayInt == Calendar.WEDNESDAY) {
327             label.setText(resource.getString("datecombobox.wed"));
328         } else if (dayInt == Calendar.THURSDAY) {
329             label.setText(resource.getString("datecombobox.thu"));
330         } else if (dayInt == Calendar.FRIDAY) {
331             label.setText(resource.getString("datecombobox.fri"));
332         } else if (dayInt == Calendar.SATURDAY){
333             label.setText(resource.getString("datecombobox.sat"));
334         }
335         days.add(label);
336         setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
337         }
338
339         setupCalendar = (Calendar JavaDoc) calendar.clone();
340         setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
341         int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
342         for (int i = 0; i < (first - 1); i++) {
343         days.add(new JLabel(""));
344         }
345         for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
346         final int day = i;
347         final JLabel label = new JLabel(String.valueOf(day));
348         label.setHorizontalAlignment(JLabel.CENTER);
349         label.setForeground(foreground);
350         label.addMouseListener(new MouseListener() {
351             public void mousePressed(MouseEvent e) {}
352             public void mouseClicked(MouseEvent e) {}
353             public void mouseReleased(MouseEvent e) {
354                 label.setOpaque(false);
355                 label.setBackground(background);
356                 label.setForeground(foreground);
357                 calendar.set(Calendar.DAY_OF_MONTH, day);
358                 comboBox.setSelectedItem(dateFormat.format(calendar.getTime()));
359                 // hide();
360
// hide is called with setSelectedItem() ... removeAll()
361
comboBox.requestFocus();
362             }
363             public void mouseEntered(MouseEvent e) {
364                 label.setOpaque(true);
365                 label.setBackground(selectedBackground);
366                 label.setForeground(selectedForeground);
367             }
368             public void mouseExited(MouseEvent e) {
369                 label.setOpaque(false);
370                 label.setBackground(background);
371                 label.setForeground(foreground);
372             }
373             });
374
375         days.add(label);
376         }
377         
378         popup.add(BorderLayout.CENTER, days);
379         popup.pack();
380     }
381     }
382
383     //////////////////////////////////////////////////////////////
384
// This is only included to provide a sample GUI
385
//////////////////////////////////////////////////////////////
386
public static void main(String JavaDoc args[]) {
387     JFrame f = new JFrame();
388     Container c = f.getContentPane();
389     c.setLayout(new FlowLayout());
390     c.add(new JLabel("Date 1:"));
391     c.add(new DateComboBox());
392     c.add(new JLabel("Date 2:"));
393     DateComboBox dcb = new DateComboBox();
394     dcb.setEditable(true);
395     c.add(dcb);
396     f.addWindowListener(new WindowAdapter() {
397         public void windowClosing(WindowEvent e) {
398             System.exit(0);
399         }
400         });
401     f.setSize(500, 200);
402     f.show();
403     }
404
405 }
406
407
408     
409
410
411
Popular Tags