source: ether_megapoli/trunk/service/implementation/gov2/noaa/pmel/sgt/swing/prop/GeoDateDialog.java @ 192

Last change on this file since 192 was 192, checked in by vmipsl, 13 years ago

Servlet _ Contour en cours _ package gov2

File size: 41.1 KB
Line 
1/*
2 * $Id: GeoDateDialog.java,v 1.2 2001/02/08 00:29:39 dwd Exp $
3 *
4 * This software is provided by NOAA for full, free and open release.  It is
5 * understood by the recipient/user that NOAA assumes no liability for any
6 * errors contained in the code.  Although this software is released without
7 * conditions or restrictions in its use, it is expected that appropriate
8 * credit be given to its author and to the National Oceanic and Atmospheric
9 * Administration should the software be included by the recipient as an
10 * element in other product development.
11 */
12package gov.noaa.pmel.sgt.swing.prop;
13
14import gov.noaa.pmel.util.GeoDate;
15
16import java.awt.*;
17import java.awt.event.*;
18import javax.swing.border.*;
19import javax.swing.*;
20import java.io.*;
21import java.net.*;
22import java.util.*;
23import java.text.*;
24import javax.swing.event.ListSelectionListener;
25import java.beans.PropertyChangeSupport;
26import java.beans.PropertyChangeListener;
27
28/**
29 * <code>GeoDateDialog</code> is a calendar, plus optionally, time, chooser
30 * that produces a date.  It allows the invoker to set the
31 * allowable range of dates by specifying an earliest and latest
32 * allowable date.  The user can select a date to within
33 * 5 minutes.  If the hour and minutes aren't needed, a flag
34 * allows the exclusion of the display of these fields. 
35 *
36 * @author Chris Windsor
37 * @version $Revision: 1.2 $, $Date: 2001/02/08 00:29:39 $
38 * @since 2.0
39 */
40public class GeoDateDialog extends JDialog
41        implements ItemListener,
42                  PropertyChangeListener,
43                   ActionListener {
44  // Get-able, Set-able variables
45  private GeoDate initialDate = new GeoDate();
46  private GeoDate earliestDateAllowed = new GeoDate();
47  private GeoDate latestDateAllowed = new GeoDate();
48  private boolean earliestCheckingEnabled = false;
49  private boolean latestCheckingEnabled = false;
50  private Font regularFont, boldFont;
51  private Color panelBackground, calBackground, selectedButnBackground;
52
53  private final static String[] months = {"Jan","Feb","Mar",
54                                          "Apr","May","Jun",
55                                          "Jul","Aug","Sep",
56                                          "Oct", "Nov","Dec"};
57  private final static String[] daysOfMonth = {" 1"," 2"," 3"," 4"," 5",
58                                               " 6"," 7"," 8"," 9","10",
59                                               "11","12","13","14","15",
60                                               "16","17","18","19","20",
61                                               "21","22","23","24","25",
62                                               "26","27","28","29","30",
63                                               "31"};
64  private final static String[] hours = {"0","1","2","3","4","5","6","7",
65                                         "8","9","10","11","12","13","14",
66                                         "15","16","17","18","19","20","21",
67                                         "22","23"};
68  private final static String[] minutes =  {"0","5","10","15","20","25",
69                                            "30","35","40","45","50","55"};
70  private final static int numWeeks = 6;
71
72  private GregorianCalendar cal;
73  private SimpleDateFormat dateFormatter;
74  private SimpleDateFormat sdf;
75  private SimpleDateFormat tsdf = new SimpleDateFormat("dd MMM yyyy ");
76  private static TimeZone tz = TimeZone.getTimeZone("GMT");
77
78  private int result_;
79  public static int OK_RESPONSE = 1;
80  public static int CANCEL_RESPONSE = 2;
81
82  private JPanel mainPanel_;
83  private JPanel calPanel, okPanel, selectionPanel;
84  private javax.swing.Box box, theBox, timeBox, monthYearBox, okBox, labelBox,
85    hrMinBox;
86  private JButton subYearButn, subMonthButn, addMonthButn, addYearButn,
87    addHourButn, subHourButn, addMinButn, subMinButn;
88  private JButton cancelButn, okButn;
89  private JToggleButton calButtons[ ];
90  private JLabel yearLabel, hourLabel, minLabel, hourMinLabel;
91  private JLabel selectionLabel;
92  private Choice monthChoice, yearChoice;
93  private JComboBox monthList, minList;
94  private JTextField hourText, yearText;
95  private Component caller;
96
97  private ButtonGroup calButtonGroup;
98   
99  private GeoDate liquidDate;
100  private int lastDaySel, lastButnSel = 1;
101  private int xloc, yloc;
102  private String title;
103  private boolean hideTime;
104  //  private JFrame aJFrame = null;
105  static private CompoundBorder cp = new CompoundBorder( 
106                        new BevelBorder( BevelBorder.RAISED ),
107                        new EmptyBorder( 2,2,2,2));
108
109  public static final int DATE = Calendar.DATE;
110  public static final int YEAR = Calendar.YEAR;
111  public static final int MONTH = Calendar.MONTH;
112  public static final int MINUTE = Calendar.MINUTE;
113  public static final int HOUR_OF_DAY = Calendar.HOUR_OF_DAY;
114
115  private boolean TRACE = false;
116  private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
117
118  // Get/Set Routines ------------------------------------------------------
119  public void setEarliestDateAllowed( GeoDate earliestDateAllowed ) {
120    this.earliestDateAllowed = earliestDateAllowed;
121    earliestCheckingEnabled = true;
122    System.out.println("Earliest date allowed: " + earliestDateAllowed);
123  }
124  public void setLatestDateAllowed( GeoDate latestDateAllowed ) {
125    this.latestDateAllowed = latestDateAllowed;
126    latestCheckingEnabled = true;
127    System.out.println("Latest date allowed: " + latestDateAllowed);
128  }
129  public GeoDate getEarliestDateAllowed() {
130    return( earliestDateAllowed );
131  }
132  public GeoDate getLatestDateAllowed() {
133    return( latestDateAllowed );
134  }
135  //  public void setTimeZone( TimeZone tz ) {
136  //    this.tz = tz;
137  //    setTimeZoneForTimeObjects( tz );
138  //  }
139
140  //  public TimeZone getTimeZone( ) {
141  //    return this.tz;
142  //  }
143
144    public void setOutputDateFormatter( SimpleDateFormat sdf) {
145      this.sdf = sdf;
146    }
147
148  public void setInitialDate( GeoDate initialDateIn) {
149    initialDate = initialDateIn;
150    liquidDate = new GeoDate( initialDate );
151    this.setTitle( composeTimeLabel( liquidDate));
152  }
153  public void setGeoDate( GeoDate dt) {
154    if (TRACE) System.out.println( "setDate entered");
155    liquidDate = new GeoDate( dt );
156    if (liquidDateWithinBounds()) {
157      updateGUIAfterLiquidDateChange();
158      this.setTitle( composeTimeLabel( liquidDate));
159    }
160  }
161  public void setTitle( String title ) {
162    this.title = title;
163  }
164  public String getTitle( ) {
165    return this.title;
166  }
167  public GeoDate getInitialDate() {
168    return( initialDate );
169  }
170  public void setRegularFont( Font regularFontIn ) {
171    regularFont = regularFontIn;
172  }
173  public Font getRegularFont() {
174    return( regularFont );
175  }
176  public void setBoldFont( Font boldFontIn ) {
177    boldFont = boldFontIn;
178  }
179  public Font getBoldFont( ) {
180    return( boldFont );
181  }
182  public void setPanelBackground( Color color ) {
183    panelBackground = color;
184  }
185  public Color getPanelBackground( ) {
186    return( panelBackground );
187  }
188  public void setCalBackground( Color color ) {
189    calBackground = color;
190  }
191  public Color getCalBackground( ) {
192    return( calBackground );
193  }
194  public void setSelectedButnBackground( Color color ) {
195    selectedButnBackground = color;
196  }
197  public Color getSelectedButnBackground( ) {
198    return( selectedButnBackground );
199  }
200  public void setHideTime( boolean ans) {
201    hideTime = ans;
202    if (ans) {
203      removeTime();
204    }
205  }
206  public boolean getHideTime() {
207    return hideTime;
208  }
209  //  public JButton getOkButn() {
210  //    return okButn;
211  //  }
212  //  public JButton getCancelButn() {
213  //    return cancelButn;
214  //  }
215  //----------------------------------------------------------------
216  // Constructor
217  public GeoDateDialog( GeoDate inDate ) {
218
219    super();
220    //    tz = TimeZone.getDefault();
221    cal = new GregorianCalendar();
222    cal.setTimeZone(tz);
223    createDateFormatter();
224    setTimeZoneForTimeObjects( );
225    setInitialDate( inDate ); 
226    finishConstruction();
227  }
228
229  //----------------------------------------------------------------
230  // Constructor
231  public GeoDateDialog( GeoDate inDate, GeoDate earliestDateAllowedIn,
232                          GeoDate latestDateAllowedIn, int xlocIn, int ylocIn) {
233
234    super();
235    //    tz = TimeZone.getDefault();
236    cal = new GregorianCalendar();
237    cal.setTimeZone(tz);
238    createDateFormatter();
239    setTimeZoneForTimeObjects( );
240    xloc = xlocIn;
241    yloc = ylocIn;
242    setInitialDate( inDate ); 
243    setEarliestDateAllowed( earliestDateAllowedIn );
244    setLatestDateAllowed( latestDateAllowedIn );
245    finishConstruction();
246  }
247
248  //----------------------------------------------------------------
249  // Constructor
250  public GeoDateDialog( ) {
251
252    super();
253    //    tz = TimeZone.getDefault();
254    cal = new GregorianCalendar();
255    cal.setTimeZone(tz);
256    createDateFormatter();
257    setTimeZoneForTimeObjects( );
258    // Initialize date to current, but round hours and minutes to 0
259    GeoDate dt = new GeoDate();
260    cal.setTime( dt );
261    computeFields( cal );
262    cal.set(HOUR_OF_DAY,0); cal.set(MINUTE,0); 
263    cal.set( cal.SECOND,0);
264    dt = new GeoDate(cal.getTime());
265    setInitialDate( dt ); 
266
267    finishConstruction();
268  }
269  //----------------------------------------------------------------
270  // Finish Construction
271  //
272  void finishConstruction( ) {
273
274    mainPanel_ = new JPanel();
275
276    this.addPropertyChangeListener( this );
277    //    mainPanel_.setSize(220 ,323);
278
279    regularFont = new Font( "Dialog", Font.PLAIN, 10);
280    boldFont = new Font( "Dialog", Font.BOLD, 10);
281    setSelectedButnBackground( new Color(240, 240, 240 ));
282    setCalBackground( new Color(200,200,200 ));
283
284    createCalendarPanel();
285    createMonthYearPanel();
286    createTimePanel();
287    createOkPanel();
288    createSelectionPanel();
289
290    theBox = box.createVerticalBox();
291    theBox.add( monthYearBox );
292    theBox.add( calPanel);
293    theBox.add( timeBox);
294    theBox.add( box.createVerticalStrut( 1 ));
295    theBox.add( selectionPanel);
296    theBox.add( okPanel);
297    theBox.add( box.createVerticalGlue()); 
298
299    theBox.validate();
300    theBox.setBackground( panelBackground );
301    theBox.setBackground( Color.white );
302    theBox.repaint();
303    //this.getContentPane().add( theBox );
304    mainPanel_.add( theBox );
305    theBox.setLocation( 10, 10 );
306    mainPanel_.setLocation( xloc, yloc);
307    this.getContentPane().add(mainPanel_);
308    validate();
309    repaint();
310
311    cal.setTime( getInitialDate());
312    computeFields( cal );
313    lastDaySel = cal.get( DATE );
314
315    resetCalendarPanel( initialDate );
316    softwareDayOfMonthClick( initialDate );
317
318    minList.setSelectedIndex( (cal.get(MINUTE)/5));
319    hourText.setText( new String(String.valueOf(cal.get(HOUR_OF_DAY))));
320    monthList.setSelectedIndex( cal.get( MONTH));
321
322  }
323  //----------------------------------------------------------------
324  // showInJFrame
325  //
326  //  show this DateTimeGetter in a JFrame; handles all window closing
327  //
328  public int showDialog(GeoDate date, int x, int y) {
329    this.setSize(220 ,323);
330    this.setLocation(x, y);
331//      aJFrame.addWindowListener( new WindowAdapter() {
332//      public void windowClosing( WindowEvent e) {
333//        closeDown();
334//      }
335//        });
336    setInitialDate(date);
337    setGeoDate(date);
338    result_ = CANCEL_RESPONSE;
339    this.setModal(true);
340    this.setVisible( true );
341    return result_;
342  }
343
344  //----------------------------------------------------------------
345  // Removes the time-related selectors
346  //
347  void removeTime() {
348    theBox.remove(timeBox); 
349    createDateFormatter();
350    updateDateLabel();
351    this.setSize( 220 ,260);
352  }
353
354  //----------------------------------------------------------------
355  //
356  // for all objects that use timezone.
357  //
358  void setTimeZoneForTimeObjects() {
359      if (TRACE) System.out.println( "setTimeZoneForTimeObjects entered");
360      if (dateFormatter != null) dateFormatter.setTimeZone( tz );
361      if (cal != null) cal.setTimeZone( tz );
362    }
363
364
365  //----------------------------------------------------------------
366  // Create date formatter; need to create this only once for use
367  // many times.
368  void createDateFormatter() {
369
370    if (TRACE) System.out.println( "createDateFormatter entered");
371    dateFormatter = new SimpleDateFormat(" dd MMM yyyy HH:mm ");
372    if (hideTime) {
373      dateFormatter = new SimpleDateFormat("dd MMM yyyy ");
374    }
375    dateFormatter.setTimeZone( tz );
376  }
377
378  //----------------------------------------------------------------
379  // create Calendar panel
380  //----------------------------------------------------------------
381  // The calendar panel has the grid layout of 7 rows, 7 columns,
382  // (One label row; 6 week rows)
383  //
384
385  void createCalendarPanel( ) {
386
387    if (TRACE) System.out.println( "createCalendarPanel entered");
388    int dayOfWeek, weekOfMonth;
389
390    JLabel jl;
391    // Create a panel for the calendar
392    calPanel = new JPanel();
393    calPanel.setLayout( new GridLayout( numWeeks+1, 7, 2, 1 ));
394    jl = new JLabel("Sun", JLabel.CENTER); jl.setFont(boldFont);
395    calPanel.add( jl);
396    jl = new JLabel("Mon", JLabel.CENTER); jl.setFont(boldFont);
397    calPanel.add( jl);
398    jl = new JLabel("Tue", JLabel.CENTER); jl.setFont(boldFont);
399    calPanel.add( jl);
400    jl = new JLabel("Wed", JLabel.CENTER); jl.setFont(boldFont);
401    calPanel.add( jl);
402    jl = new JLabel("Thu", JLabel.CENTER); jl.setFont(boldFont);
403    calPanel.add( jl);
404    jl = new JLabel("Fri", JLabel.CENTER); jl.setFont(boldFont);
405    calPanel.add( jl);
406    jl = new JLabel("Sat", JLabel.CENTER); jl.setFont(boldFont);
407    calPanel.add( jl);
408    calPanel.setBorder( new EmptyBorder( 2,2,2,2));
409
410    calButtonGroup = new ButtonGroup();
411    calButtons = new JToggleButton[ numWeeks * 7 ];
412    for (int i = 0; i < (7*numWeeks); i++ ) {
413      calButtons[ i ] = new JToggleButton("  ");
414      calButtons[ i ].setBorder( cp );
415      calButtons[ i ].setContentAreaFilled( true );
416      calButtons[ i ].addActionListener( this );
417      calButtons[ i ].setFont(regularFont);
418      calPanel.add( calButtons[ i ] );
419      calButtonGroup.add( calButtons[ i ] );
420      calButtons[ i ].setMinimumSize( new Dimension( 17, 21 ));
421      calButtons[ i ].setMaximumSize( new Dimension( 17, 21 ));
422      calButtons[ i ].setSize( new Dimension( 17, 21 ));
423    }
424
425  }  // createCalendarPanel
426
427  //----------------------------------------------------------------
428  // reset Calendar Panel when the date changes to reflect new month.
429  //----------------------------------------------------------------
430  void resetCalendarPanel( GeoDate newDate ) {
431
432    if (TRACE) System.out.println( "resetCalendarPanel entered");
433    int dayOfWeek, weekOfMonth;
434    String[][] gridLabels = new String[7][numWeeks];
435    GregorianCalendar cal1 = new GregorianCalendar();
436    cal1.setTimeZone( tz );
437
438    // Set labels in grid to "  "
439    for (dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {   // monday -> sunday
440      for (weekOfMonth = 0; weekOfMonth < numWeeks; weekOfMonth++) {
441        gridLabels[ dayOfWeek][ weekOfMonth ] = "  ";
442      }
443    }
444
445    // Get first day of this month
446    cal1.setTime( newDate );
447    computeFields( cal1 );
448    cal1.set( cal1.DATE, 1 );
449    Date firstThisMonth = cal1.getTime();
450
451    //System.out.println(" firstThisMonth: " + tsdf.format( firstThisMonth));
452    // Get first of next month's date
453    cal1.setTime( firstThisMonth );
454    computeFields( cal1 );
455    dayOfWeek = cal1.get( cal1.DAY_OF_WEEK ) - 1;       // added the subtract 12/99
456    //System.out.println(" day of week is: " + dayOfWeek);
457
458    // Now set calendar to next month
459    if ((cal1.get(cal1.MONTH)+1) == 13) {  // crossing over to the next year
460      cal1.set(cal1.MONTH, 0 );
461      cal1.set(cal1.YEAR, cal1.get( cal1.YEAR ) +1 );
462    }
463    else
464      cal1.set(cal1.MONTH, cal1.get( cal1.MONTH )+1 );
465
466
467    Date firstNextMonth = cal1.getTime();
468    //System.out.println(" firstNextMonth: " + tsdf.format( firstNextMonth));
469
470    long curTime = firstThisMonth.getTime();
471    long endTime = firstNextMonth.getTime();
472    cal1.setTime( firstThisMonth);
473    computeFields( cal1 );
474
475    weekOfMonth = 0;
476    int dayOfMonth = 1;
477    while (curTime < endTime) {
478      // Set labels in grid
479      if (dayOfMonth != 32) // October; daylight savings time causes bug
480        gridLabels[ dayOfWeek][ weekOfMonth ] = daysOfMonth[ dayOfMonth-1 ];
481
482      dayOfWeek++;
483      dayOfMonth++;
484      if (dayOfWeek > 6) {
485        dayOfWeek = 0;
486        weekOfMonth++;
487      }
488      curTime+= (24 * 60 * 60 * 1000);  // add 24 hours
489    }
490
491    int ithButn = 0;
492    for (weekOfMonth = 0; weekOfMonth < numWeeks; weekOfMonth++) {
493      for (dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {// monday -> sunday
494        if (gridLabels[ dayOfWeek][weekOfMonth].equals("  ")) {
495          calButtons[ ithButn ].setText( "  ");
496          calButtons[ ithButn ].setVisible(false);
497        }
498        else {
499          calButtons[ ithButn ].setText( 
500                                        gridLabels[ dayOfWeek][weekOfMonth]);
501          calButtons[ ithButn ].setVisible(true);
502        }
503        ithButn++;
504      }
505    }
506  }
507  //----------------------------------------------------------------
508  // closeDown
509  //
510  void closeDown() {
511    this.setVisible( false );
512  }
513
514  public GeoDate getGeoDate() {
515    return liquidDate;
516  }
517
518  //----------------------------------------------------------------
519  void softwareDayOfMonthClick( GeoDate dt) {
520
521    if (TRACE) System.out.println( "softwareDayOfMonthClick entered");
522    cal.setTime( dt );
523    computeFields( cal );
524    int date = cal.get( DATE );
525    int idx = 0;
526    for (int i = 0; i < calButtons.length; i++) {
527      if (calButtons[i].getText().equals( daysOfMonth[ date-1 ])) {
528        calButtons[i].doClick(); 
529      }
530    }
531  } 
532
533  //----------------------------------------------------------------
534  void selectDay( int date) {
535
536    if (TRACE) System.out.println( "selectDay entered");
537    if (calButtons != null) {
538      for (int i = 0; i < calButtons.length; i++) {
539        if (calButtons[i].getText().equals( daysOfMonth[ date-1 ])) {
540          lastButnSel = i;
541          lastDaySel = date;
542          break;
543        }
544      }
545    }
546  }  // selectDay
547
548  // --------------------------------------------------------------
549  // Compose time label
550  String composeTimeLabel( GeoDate dt ) {
551    return( dateFormatter.format( dt ));
552  }
553  //----------------------------------------------------------------
554  // computeFields
555  //  forces the Calendar object to compute its fields.  (Unfortunately,
556  //  the computeFields method of the object is protected, so I can't
557  //   call it.)
558  //----------------------------------------------------------------
559  void computeFields( Calendar caln ) {
560    {int yrr=caln.get(caln.YEAR);} // FORCE a call to computeFields
561  }
562
563  //----------------------------------------------------------------
564  // update Date Label
565  //----------------------------------------------------------------
566  void updateDateLabel( ) {
567
568    //this.setTitle( composeTimeLabel( liquidDate ));
569    selectionLabel.setText( composeTimeLabel( liquidDate ));
570  }
571  //----------------------------------------------------------------
572  // create Month/Year panel
573  //----------------------------------------------------------------
574  // The Month/Year panel has the following grid bag layout structure:
575  //
576  //         x-0    x-1    x-2    x-3    x-4    x-5    x-6   
577  //         ------ ------ ------ ------ ------ ------ ------
578  //  y-0:   subYea subMon month  month  year   addMon addYea
579
580  void createMonthYearPanel() {
581
582    if (TRACE) System.out.println( "createMonthYearPanel entered");
583    subMonthButn = new JButton("<<");
584    subMonthButn.setFont( regularFont );
585    subMonthButn.setBorder( cp );
586    subMonthButn.addActionListener( this );
587    subMonthButn.setBackground( calBackground );
588    subMonthButn.setAlignmentY( 0.5f );
589
590    addMonthButn = new JButton(">>");
591    addMonthButn.setFont( regularFont );
592    addMonthButn.setBorder( cp );
593    addMonthButn.addActionListener( this );
594    addMonthButn.setBackground( calBackground );
595    addMonthButn.setAlignmentY( 0.5f );
596
597    monthList = new JComboBox( months );
598    monthList.setFont( regularFont );
599    monthList.addItemListener( this );
600    monthList.setAlignmentY( 0.5f );
601
602    yearText = new JTextField( new String( String.valueOf(cal.get( YEAR))));
603    yearText.setBackground(calBackground);
604    yearText.addActionListener( this );
605    yearText.setFont( regularFont );
606    int x = subMonthButn.getPreferredSize().width*3;
607    int y = subMonthButn.getPreferredSize().height;
608    yearText.setPreferredSize( new Dimension( x,y));
609    yearText.setMaximumSize( new Dimension( x,y));
610    yearText.setAlignmentY( .5f );
611
612    subYearButn = new JButton("<<");
613    subYearButn.setFont( regularFont );
614    subYearButn.setBorder( cp );
615    subYearButn.addActionListener( this );
616    subYearButn.setBackground( calBackground );
617    subYearButn.setAlignmentY( .5f );
618
619    addYearButn = new JButton(">>");
620    addYearButn.setFont( regularFont );
621    addYearButn.setBorder( cp );
622    addYearButn.addActionListener( this );
623    addYearButn.setBackground( calBackground );
624    addYearButn.setAlignmentY( .5f );
625
626    monthYearBox = box.createHorizontalBox();
627
628
629    monthYearBox.add( box.createHorizontalGlue());
630    monthYearBox.add( subMonthButn );
631    monthYearBox.add( addMonthButn );
632    monthYearBox.add( monthList );
633    monthYearBox.add( box.createHorizontalStrut(1));
634    monthYearBox.add( yearText );
635    monthYearBox.add( subYearButn );
636    monthYearBox.add( addYearButn );
637    monthYearBox.add( box.createHorizontalGlue());
638  }
639
640  //----------------------------------------------------------------
641  // Reset MonthYear Panel
642  public void resetMonthYearPanel( GeoDate newDate ) {
643    if (TRACE) System.out.println( "resetMonthYearPanel entered");
644    cal.setTime( newDate );
645    computeFields( cal );
646    int m = cal.get( MONTH );
647    Integer yr = new Integer( cal.get( YEAR));
648
649    monthList.setVisible(false );
650    monthList.setSelectedIndex( m);
651    monthList.setVisible( true);
652
653    int yr1 = Integer.parseInt( yearText.getText().trim());
654    if (yr.intValue() != yr1) {
655      yearText.setText( yr.toString() );
656    }
657  }
658  //----------------------------------------------------------------
659  // Create Time Panel
660
661  void createTimePanel () {
662
663    if (TRACE) System.out.println( "createTimePanel entered");
664    hourLabel = new JLabel("Hour(0-23)        ");
665    hourLabel.setFont( boldFont );
666
667    minLabel = new JLabel( "Minute    ");
668    minLabel.setFont( boldFont );
669
670    JLabel colonLabel = new JLabel( ":");
671    Font f = new Font( "Dialog", Font.BOLD, 12);
672    colonLabel.setFont( f );
673
674    subHourButn = new JButton("<<");
675    subHourButn.setFont( regularFont );
676    subHourButn.setBorder( cp );
677    subHourButn.addActionListener( this );
678    subHourButn.setBackground( calBackground );
679    subHourButn.setAlignmentY( 0.5f );
680
681    addHourButn = new JButton(">>");
682    addHourButn.setFont( regularFont );
683    addHourButn.setBorder( cp );
684    addHourButn.addActionListener( this );
685    addHourButn.setBackground( calBackground );
686    addHourButn.setAlignmentY( 0.5f );
687
688    hourText = new JTextField(); 
689    hourText.setText("     00");
690    hourText.setFont( regularFont );
691    hourText.setBackground(calBackground);
692    hourText.addActionListener( this );
693    hourText.setHorizontalAlignment( JTextField.RIGHT );
694
695    int x = addHourButn.getPreferredSize().width * 2;
696    int y = addHourButn.getPreferredSize().height;
697    hourText.setPreferredSize( new Dimension( x, y) );
698    hourText.setMaximumSize( hourText.getPreferredSize());
699    hourText.setSize( hourText.getPreferredSize());
700    hourText.setAlignmentY( .5f );
701
702
703    minList = new JComboBox( minutes );
704    minList.addItemListener( this );
705    minList.setFont( regularFont );
706    x = addHourButn.getPreferredSize().width * 2;
707    y = addHourButn.getPreferredSize().height;
708    minList.setPreferredSize( new Dimension( x,y ));
709    minList.setMaximumSize( minList.getPreferredSize());
710    minList.setSize( minList.getPreferredSize());
711    minList.setAlignmentY( .5f );
712
713    subMinButn = new JButton("<<");
714    subMinButn.setFont( regularFont );
715    subMinButn.setBorder( cp );
716    subMinButn.addActionListener( this );
717    subMinButn.setBackground( calBackground );
718    subMinButn.setAlignmentY( .5f );
719
720    addMinButn = new JButton(">>");
721    addMinButn.setFont( regularFont );
722    addMinButn.setBorder( cp );
723    addMinButn.addActionListener( this );
724    addMinButn.setBackground( calBackground );
725    addMinButn.setAlignmentY( .5f );
726
727
728    labelBox = box.createHorizontalBox();
729    labelBox.add( box.createHorizontalGlue());
730    labelBox.add( hourLabel );
731    labelBox.add( box.createHorizontalStrut(1));
732    labelBox.add( minLabel );
733    labelBox.add( box.createHorizontalGlue());
734
735    hrMinBox = box.createHorizontalBox();
736    hrMinBox.add( box.createHorizontalGlue());
737    hrMinBox.add( subHourButn );
738    hrMinBox.add( addHourButn );
739    hrMinBox.add( hourText );
740    hrMinBox.add( box.createHorizontalStrut(5));
741    //hrMinBox.add( colonLabel );
742    hrMinBox.add( minList );
743    hrMinBox.add( subMinButn );
744    hrMinBox.add( addMinButn );
745    hrMinBox.add( box.createHorizontalGlue());
746
747    timeBox = box.createVerticalBox();
748    timeBox.add( box.createVerticalGlue());
749    timeBox.add( labelBox );
750    timeBox.add( hrMinBox );
751    timeBox.add( box.createVerticalGlue());
752  }
753
754  void createSelectionPanel() {
755    if (TRACE) System.out.println( "createSelectionPanel entered");
756    selectionLabel = new JLabel("ddd mmm dd hh:mm yyyy");
757    selectionLabel.setBackground( Color.red );
758    selectionLabel.setForeground( Color.black );
759    selectionPanel = new JPanel();
760    selectionPanel.add( selectionLabel );
761    int x = selectionPanel.getPreferredSize().width;
762    int y = 15;
763    //selectionPanel.setPreferredSize( new Dimension( x,y));
764    //selectionPanel.setMaximumSize( new Dimension( x,y));
765    //selectionPanel.setBackground( Color.yellow );
766    updateDateLabel();
767  }
768  //----------------------------------------------------------------
769  // create the okay/cancel panel
770  void createOkPanel() {
771
772    if (TRACE) System.out.println( "createOkPanel entered");
773    okButn = new JButton(    "OK"); 
774    okButn.addActionListener( this );
775    okButn.setBackground( calBackground );
776    okButn.setMinimumSize( new Dimension( 51, 25 ));
777    okButn.setMaximumSize( new Dimension( 51, 25 ));
778
779    cancelButn = new JButton("Cancel");
780    cancelButn.addActionListener( this );
781    cancelButn.setBackground( calBackground );
782    cancelButn.setMinimumSize( new Dimension( 73, 25 ));
783    cancelButn.setMaximumSize( new Dimension( 73, 25 ));
784
785    okPanel = new JPanel();
786    okPanel.setLayout( new GridLayout(1,2));
787    okPanel.add( okButn);
788    okPanel.add( cancelButn);
789  }  // create okPanel
790
791  //----------------------------------------------------------------
792  // handleHourChange
793  void handleHourChange(){
794    if (TRACE) System.out.println( "handleHourChange entered");
795    try {
796      cal.setTime( liquidDate );
797      computeFields( cal );
798      int prevHr = cal.get(HOUR_OF_DAY);   // hang on to old value
799      int hr = Integer.parseInt( hourText.getText().trim());
800      hr = validateHours( hr );
801      hourText.setText( (new Integer(hr)).toString() );
802      cal.set( HOUR_OF_DAY, hr );
803      liquidDate = new GeoDate(cal.getTime());
804      if (!liquidDateWithinBounds()) {  // restore old value
805        cal.set( HOUR_OF_DAY, prevHr );
806        liquidDate = new GeoDate(cal.getTime());
807        hourText.setText( (new Integer(prevHr)).toString() );
808      }
809      updateDateLabel();
810    } catch (NumberFormatException e) {
811    }
812  }
813  //----------------------------------------------------------------
814  // handleYearChange
815  void handleYearChange(){
816    if (TRACE) System.out.println( "handleYearChange entered");
817    try {
818      cal.setTime( liquidDate );
819      computeFields( cal );
820      int prevYr = cal.get(YEAR);   // hang on to old value
821      int yr = Integer.parseInt( yearText.getText().trim());
822      //yr = validateYear( yr );
823      yearText.setText( (new Integer(yr)).toString() );
824      cal.set( YEAR, yr );
825      liquidDate = new GeoDate(cal.getTime());
826      if (!liquidDateWithinBounds()) {  // restore old value
827        //boundsMsg();
828        cal.set( YEAR, prevYr );
829        liquidDate = new GeoDate(cal.getTime());
830        yearText.setText( (new Integer(prevYr)).toString() );
831      }
832      else {
833        updateGUIAfterLiquidDateChange();
834      }
835      updateDateLabel();
836    } catch (NumberFormatException e) {
837    }
838  }
839  //----------------------------------------------------------------
840  // Validate Hours
841  int validateHours( int hr) {
842    if (TRACE) System.out.println( "validateHours entered");
843    if (hr < 0) return(0);
844    if (hr > 23) return(23);
845    return( hr );
846  }
847  //----------------------------------------------------------------
848  // check Date within range
849  boolean liquidDateWithinBounds( ) {
850
851    if (TRACE) System.out.println( "liquidDateWithinBounds entered");
852    /*
853      cal.setTime( earliestDateAllowed );
854      computeFields( cal );
855      System.out.println(" Floor date is: " +
856      " year " + cal.get( YEAR) +
857      " month " + cal.get( MONTH) +
858      " date " + cal.get( DATE) +
859      " hour " + cal.get( cal.HOUR) +
860      " min " + cal.get( MINUTE));
861
862      cal.setTime( latestDateAllowed );
863      computeFields( cal );
864      System.out.println(" Latest date is: " +
865      " year " + cal.get( YEAR) +
866      " month " + cal.get( MONTH) +
867      " date " + cal.get( DATE) +
868      " hour " + cal.get( cal.HOUR) +
869      " min " + cal.get( MINUTE));
870
871      cal.setTime( liquidDate );
872      computeFields( cal );
873      System.out.println(" Liquid date is: " +
874      " year " + cal.get( YEAR) +
875      " month " + cal.get( MONTH) +
876      " date " + cal.get( DATE) +
877      " hour " + cal.get( cal.HOUR) +
878      " min " + cal.get( MINUTE));
879    */
880
881    if (earliestCheckingEnabled) {
882      System.out.println("liquidDate is: " + liquidDate);
883      System.out.println("earliestDateAllowed is: " + earliestDateAllowed);
884      if (liquidDate.getTime() < earliestDateAllowed.getTime()) {
885        lowerBoundMsg();
886        return (false);
887      }
888    }
889    if (latestCheckingEnabled) {
890      if (liquidDate.getTime() > latestDateAllowed.getTime()) {
891        upperBoundMsg();
892        return( false );
893      }
894    }
895    return( true );
896  }
897  //----------------------------------------------------------------
898  //
899  void lowerBoundMsg() {
900    if (TRACE) System.out.println( "lowerBoundMsg entered");
901    JOptionPane.showMessageDialog(this, 
902                                  (new String("Lower bound restricted to " + composeTimeLabel( getEarliestDateAllowed()))),
903                                  "Calendar Bounds Exception",
904                                  JOptionPane.WARNING_MESSAGE);
905  }
906  //----------------------------------------------------------------
907  //
908  void upperBoundMsg() {
909    if (TRACE) System.out.println( "upperBoundMsg entered");
910    JOptionPane.showMessageDialog(this, 
911                                  (new String("Upper bound restricted to " + composeTimeLabel( getLatestDateAllowed()))),
912                                  "Calendar Bounds Exception",
913                                  JOptionPane.WARNING_MESSAGE);
914  }
915  //----------------------------------------------------------------
916  // attempt to add or subract a year
917  void attemptToAddOrSubtractAYear( int numYears ) {
918    if (TRACE) System.out.println( "attemptToAddOrSubtractAYear entered");
919    cal.setTime( liquidDate );
920    computeFields( cal );
921    int yr = cal.get(YEAR) + numYears;
922    cal.set( YEAR, yr );
923    liquidDate = new GeoDate(cal.getTime());
924    if (liquidDateWithinBounds()) {
925      updateGUIAfterLiquidDateChange();
926    }
927    else {  // drops below floor or above ceiling; return to previous value
928      cal.set( YEAR, (cal.get(YEAR) - numYears) );
929      liquidDate = new GeoDate(cal.getTime());
930    }
931  }
932  //----------------------------------------------------------------
933  // update GUI components after liquid Date change
934  void updateGUIAfterLiquidDateChange() {
935    if (TRACE) System.out.println( "updateGUIAfterLIquidDateChange entered");
936    resetMonthYearPanel( liquidDate );
937    resetCalendarPanel( liquidDate );
938    softwareDayOfMonthClick( liquidDate );
939    updateDateLabel();
940  }
941  //----------------------------------------------------------------
942  // item State Changed
943  public void itemStateChanged( ItemEvent itemEvent) {
944    if (TRACE) System.out.println( "itemStateChanged entered");
945
946    if (itemEvent.getSource() == monthList) {
947
948      int mon = monthList.getSelectedIndex();
949      cal.setTime( liquidDate );
950      computeFields( cal );
951      int prevMon = cal.get(MONTH);
952
953      if (prevMon != mon) {
954        cal.set( MONTH, mon );
955        liquidDate = new GeoDate(cal.getTime());
956        if (!liquidDateWithinBounds()) {
957          cal.set(MONTH, prevMon );
958          liquidDate = new GeoDate(cal.getTime());
959        }
960        updateGUIAfterLiquidDateChange();
961      }
962    }
963    else if (itemEvent.getSource() == minList) {
964      int min = Integer.parseInt( (String) minList.getSelectedItem());
965      cal.setTime( liquidDate );
966      computeFields( cal );
967      int oldMin = cal.get(MINUTE);
968      cal.set(MINUTE, min  );
969      liquidDate = new GeoDate(cal.getTime());
970      if (!liquidDateWithinBounds()) {
971        cal.set(MINUTE, oldMin);
972        liquidDate = new GeoDate(cal.getTime());
973        minList.setVisible(false);
974        minList.setSelectedIndex( oldMin/5 );
975        minList.setVisible(true);
976      }
977      updateDateLabel();
978    }
979  }
980  //----------------------------------------------------------------
981  // Action
982  public void actionPerformed( ActionEvent event ) {
983    if (TRACE) System.out.println( "actionPerformed entered");
984    Object source = event.getSource();
985    int mon = 0;
986    int prevMon = 0;
987    int yr = 0;
988    int day = 0;
989    int inputDayOfMonth;
990
991    if (source == okButn) {
992      // First, get the hour from the TextField in case user didn't hit
993      // return
994      handleHourChange();
995      if (sdf != null) {
996        pcs.firePropertyChange("FormattedDateTime",
997                               sdf.format( getInitialDate()), 
998                               sdf.format(liquidDate));
999      }
1000      pcs.firePropertyChange("DateTime",
1001                             getInitialDate(),
1002                             liquidDate);
1003      result_ = OK_RESPONSE;
1004      closeDown();
1005    }
1006    else if (source == cancelButn) {
1007      result_ = CANCEL_RESPONSE;
1008      closeDown();
1009    }
1010    else if (source == subYearButn) {
1011      attemptToAddOrSubtractAYear( -1 );
1012    }
1013    else if (source == addYearButn) {
1014      attemptToAddOrSubtractAYear( 1 );
1015    }
1016    else if (source == subMonthButn) {
1017      cal.setTime( liquidDate );
1018      computeFields( cal );
1019      mon = cal.get(MONTH) - 1;
1020      if (mon == -1) { // Jan --> Dec
1021        mon = 11;
1022        cal.set( MONTH, mon );
1023        yr = cal.get( YEAR ) - 1;
1024        cal.set( YEAR, yr );
1025        liquidDate = new GeoDate(cal.getTime());
1026        if (!liquidDateWithinBounds()) {
1027          yr = cal.get( YEAR ) + 1;
1028          cal.set( YEAR, yr);
1029          liquidDate = new GeoDate(cal.getTime());
1030        }
1031      }
1032      cal.set( MONTH, mon);
1033      liquidDate = new GeoDate(cal.getTime());
1034      if (!liquidDateWithinBounds()) {
1035        mon = mon + 1;
1036        if (mon == 12) mon = 0;
1037        cal.set( MONTH, mon );
1038        liquidDate = new GeoDate(cal.getTime());
1039      }
1040      updateGUIAfterLiquidDateChange();
1041    }
1042    else if (source == addMonthButn) {
1043      cal.setTime( liquidDate );
1044      computeFields( cal );
1045      mon = cal.get(MONTH) + 1;
1046      if (mon == 12) {
1047        mon = 0;
1048        cal.set( MONTH, 0 );
1049        yr = cal.get(YEAR) + 1;
1050        cal.set( YEAR, yr );
1051        liquidDate = new GeoDate(cal.getTime());
1052        if (!liquidDateWithinBounds()) {
1053          cal.set( YEAR, cal.get(YEAR) - 1);
1054          liquidDate = new GeoDate(cal.getTime());
1055        }
1056      }
1057      cal.set(MONTH, mon );
1058      liquidDate = new GeoDate(cal.getTime());
1059      if (!liquidDateWithinBounds()) {
1060        mon = mon - 1;
1061        if (mon == -1) mon = 11;
1062        cal.set( MONTH, mon );
1063        liquidDate = new GeoDate(cal.getTime());
1064      }
1065      updateGUIAfterLiquidDateChange();
1066    }
1067    else if (source == hourText) {
1068      handleHourChange();
1069    }
1070    else if (source == yearText) {
1071      handleYearChange();
1072    }
1073    else if (source == subHourButn) {
1074      try {
1075        // User may have changed the hour text without hitting "return"
1076        // so must synchronize the value in TextField with our variables
1077        handleHourChange();
1078        // Now, get the value in TextField and decrement
1079        int hr = Integer.parseInt( hourText.getText().trim());
1080        hr--;
1081        if (hr == -1) {
1082          hr = 23;
1083        }
1084        hourText.setText( (new Integer(hr)).toString() );
1085        handleHourChange();
1086      } catch (NumberFormatException e) {
1087      }
1088    }
1089    else if (source == addHourButn) {
1090      try {
1091        // User may have changed the hour text without hitting "return"
1092        // so must synchronize the value in TextField with our variables
1093        handleHourChange();
1094        // Now, get the value in TextField and decrement
1095        int hr = Integer.parseInt( hourText.getText().trim());
1096        hr++;
1097        if (hr == 24) {
1098          hr = 0;
1099        }
1100        hourText.setText( (new Integer(hr)).toString() );
1101        handleHourChange();
1102      } catch (NumberFormatException e) {
1103      }
1104    }
1105    else if (source == subMinButn) {
1106      try {
1107        int min = Integer.parseInt( (String) minList.getSelectedItem());
1108        min  = min - 5;
1109        if (min == -5) {
1110          min = 55;
1111        }
1112        cal.setTime( liquidDate );
1113        computeFields( cal );
1114        int oldMin = cal.get( MINUTE);
1115        cal.set( MINUTE, min );
1116        liquidDate = new GeoDate(cal.getTime());
1117        if (!liquidDateWithinBounds()) {
1118          cal.set( MINUTE,oldMin);
1119          liquidDate = new GeoDate(cal.getTime());
1120          min = oldMin;
1121        }
1122        minList.setVisible(false);
1123        minList.setSelectedIndex( min/5 );
1124        minList.setVisible(true);
1125        updateDateLabel();
1126      } catch (NumberFormatException e) {
1127      }
1128    }
1129    else if (source == addMinButn) {
1130      try {
1131        int min = Integer.parseInt( (String) minList.getSelectedItem());
1132        min  = min + 5;
1133        if (min == 60) {
1134          min = 0;
1135        }
1136        cal.setTime( liquidDate );
1137        computeFields( cal );
1138        int oldMin = cal.get(MINUTE);
1139        cal.set(MINUTE, min );
1140        liquidDate = new GeoDate(cal.getTime());
1141        if (!liquidDateWithinBounds()) {
1142          cal.set( MINUTE, oldMin);
1143          liquidDate = new GeoDate(cal.getTime());
1144          min = oldMin;
1145        }
1146        minList.setVisible(false);
1147        minList.setSelectedIndex( min/5 );
1148        minList.setVisible(true);
1149        updateDateLabel();
1150      } catch (NumberFormatException e) {
1151      }
1152    }
1153    else if (source == monthList) {
1154    }
1155    else { // must be from the calendar
1156      try {
1157        inputDayOfMonth = Integer.parseInt( event.getActionCommand().trim());
1158        cal.setTime( liquidDate );
1159        computeFields( cal );
1160        int lastDate = cal.get(DATE);
1161        cal.set(DATE, inputDayOfMonth );
1162        liquidDate = new GeoDate(cal.getTime());
1163        if (liquidDateWithinBounds()) {
1164          selectDay( inputDayOfMonth);
1165          updateDateLabel();
1166        }
1167        else {
1168          cal.set(DATE, lastDate );
1169          liquidDate = new GeoDate(cal.getTime());
1170        }
1171      } catch (NumberFormatException e) {
1172        System.out.println(" !!! Trouble with " + event.getActionCommand());
1173      }
1174    }
1175  }
1176
1177  public GeoDate getDate() {
1178    return liquidDate;
1179  }
1180
1181  public void propertyChange( java.beans.PropertyChangeEvent event) {
1182    if (TRACE) System.out.println( "propertyChange entered");
1183    Object obj = event.getSource();
1184    this.setTitle( composeTimeLabel( liquidDate));
1185    if (event.getPropertyName().equals("DateTime")) {
1186      /*
1187        System.out.println(" Property Change, old value: " +
1188        composeTimeLabel( (Date) event.getOldValue()) + " new value: " +
1189        composeTimeLabel( (Date) event.getNewValue()));
1190      */
1191    }
1192    else if (event.getPropertyName().equals("FormattedDateTime")) {
1193    }
1194  }
1195  public void addPropertyChangeListener( PropertyChangeListener l ) {
1196    pcs.addPropertyChangeListener( l );
1197  }
1198  public void removePropertyChangeListener( PropertyChangeListener l ) {
1199    pcs.removePropertyChangeListener( l );
1200  }
1201
1202
1203
1204  // ----------------------------------------------------------------
1205  //
1206  public static void main(String args[]) {
1207
1208    GeoDateDialog dtg = new GeoDateDialog();
1209    dtg.setOutputDateFormatter( new SimpleDateFormat(" dd MMM yyyy HH:mm "));
1210
1211    /*
1212      JFrame jf = new JFrame();
1213      jf.setVisible( true );
1214      jf.setSize(220 ,323);
1215      jf.getContentPane().add( dtg );
1216      jf.invalidate();
1217      jf.validate();
1218      jf.addWindowListener( new WindowAdapter() {
1219      public void windowClosing( WindowEvent e) {
1220      Window w = e.getWindow();
1221      w.setVisible( false );
1222      w.dispose();
1223      System.exit( 0 );
1224      }
1225      });
1226    */
1227
1228    int result = dtg.showDialog(new GeoDate(), 200, 200);
1229
1230    System.out.println("Result = " + result);
1231    System.out.println("Date = " + dtg.getGeoDate().toString());
1232
1233    dtg.addPropertyChangeListener( new PropertyChangeListener() {
1234        public void propertyChange( java.beans.PropertyChangeEvent event) {
1235          if (event.getPropertyName().equals("FormattedDateTime")) {
1236            System.out.println(" MAIN Property Change, old value: " + 
1237                               (String) event.getOldValue() + " new value: " +
1238                               (String) event.getNewValue());
1239          }
1240        }
1241      });
1242  }
1243}
Note: See TracBrowser for help on using the repository browser.