Custom dialog box to enter dates : Dialog « Swing Components « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Swing Components » DialogScreenshots 
Custom dialog box to enter dates
   
/**
 *  This file is part of the jcrontab package
 *  Copyright (C) 2002 Alexandre Pereira Calsavara
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA 02111-1307, USA
 *
 *  For questions, suggestions:
 *
 *  iolalla@yahoo.com
 *
 */

import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;


/**
 * Custom dialog box to enter dates. The <code>DateChooser</code>
 * class presents a calendar and allows the user to visually select a
 * day, month and year so that it is impossible to enter an invalid
 * date.
 @author $Author: iolalla $
 @version $Revision: 1.1 $
 **/
public class DateChooser extends JDialog 
    implements ItemListener, MouseListener, FocusListener, KeyListener, ActionListener
{
    /** Names of the months. */
    private static final String[] MONTHS = 
  new String[] {
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
  };

    /** Names of the days of the week. */
    private static final String[] DAYS =
  new String[] {
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat"
  };

    /** Text color of the days of the weeks, used as column headers in
        the calendar. */
    private static final Color WEEK_DAYS_FOREGROUND = Color.black;

    /** Text color of the days' numbers in the calendar. */
    private static final Color DAYS_FOREGROUND = Color.blue;

    /** Background color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_FOREGROUND = Color.white;

    /** Text color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_BACKGROUND = Color.blue;

    /** Empty border, used when the calendar does not have the focus. */
    private static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(1,1,1,1);

    /** Border used to highlight the selected day when the calendar
        has the focus. */
    private static final Border FOCUSED_BORDER = BorderFactory.createLineBorder(Color.yellow,1);

    /** First year that can be selected. */
    private static final int FIRST_YEAR = 1900;

    /** Last year that can be selected. */
    private static final int LAST_YEAR = 2100;

    /** Auxiliary variable to compute dates. */
    private GregorianCalendar calendar;

    /** Calendar, as a matrix of labels. The first row represents the
        first week of the month, the second row, the second week, and
        so on. Each column represents a day of the week, the first is
        Sunday, and the last is Saturday. The label's text is the
        number of the corresponding day. */
    private JLabel[][] days;

    /** Day selection control. It is just a panel that can receive the
        focus. The actual user interaction is driven by the
        <code>DateChooser</code> class. */
    private FocusablePanel daysGrid;

    /** Month selection control. */
    private JComboBox month;

    /** Year selection control. */
    private JComboBox year;

    /** "Ok" button. */
    private JButton ok;

    /** "Cancel" button. */
    private JButton cancel;

    /** Day of the week (0=Sunday) corresponding to the first day of
        the selected month. Used to calculate the position, in the
        calendar ({@link #days}), corresponding to a given day. */
    private int offset;

    /** Last day of the selected month. */
    private int lastDay;

    /** Selected day. */
    private JLabel day;

    /** <code>true</code> if the "Ok" button was clicked to close the
        dialog box, <code>false</code> otherwise. */
    private boolean okClicked;



    /**
     * Custom panel that can receive the focus. Used to implement the
     * calendar control.
     **/
    private static class FocusablePanel extends JPanel
    {
  /**
   * Constructs a new <code>FocusablePanel</code> with the given
   * layout manager.
   *
   @param layout layout manager
   **/
  public FocusablePanelLayoutManager layout ) {
      superlayout );
  }


  /**
   * Always returns <code>true</code>, since
   * <code>FocusablePanel</code> can receive the focus.
   *
   @return <code>true</code>
   **/
  public boolean isFocusTraversable() {
      return true;
  }
    }



    /**
     * Initializes this <code>DateChooser</code> object. Creates the
     * controls, registers listeners and initializes the dialog box.
     **/
    private void construct()
    {
  calendar = new GregorianCalendar();

  month = new JComboBox(MONTHS);
  month.addItemListenerthis );

  year = new JComboBox();
  for int i=FIRST_YEAR; i<=LAST_YEAR; i++ )
      year.addItemInteger.toString(i) );
  year.addItemListenerthis );

  days = new JLabel[7][7];
  for int i=0; i<7; i++ ) {
      days[0][inew JLabel(DAYS[i],JLabel.RIGHT);
      days[0][i].setForegroundWEEK_DAYS_FOREGROUND );
  }
  for int i=1; i<7; i++ )
      for int j=0; j<7; j++ )
    {
        days[i][jnew JLabel(" ",JLabel.RIGHT);
        days[i][j].setForegroundDAYS_FOREGROUND );
        days[i][j].setBackgroundSELECTED_DAY_BACKGROUND );
        days[i][j].setBorderEMPTY_BORDER );
        days[i][j].addMouseListenerthis );
    }

  ok = new JButton("Ok");
  ok.addActionListenerthis );
  cancel = new JButton("Cancel");
  cancel.addActionListenerthis );

  JPanel monthYear = new JPanel();
  monthYear.addmonth );
  monthYear.addyear );

  daysGrid = new FocusablePanel(new GridLayout(7,7,5,0));
  daysGrid.addFocusListenerthis );
  daysGrid.addKeyListenerthis );
  for int i=0; i<7; i++ )
      for int j=0; j<7; j++ )
    daysGrid.adddays[i][j] );
  daysGrid.setBackgroundColor.white );
  daysGrid.setBorderBorderFactory.createLoweredBevelBorder() );
  JPanel daysPanel = new JPanel();
  daysPanel.adddaysGrid );

  JPanel buttons = new JPanel();
  buttons.addok );
  buttons.addcancel );

  Container dialog = getContentPane();
  dialog.add"North", monthYear );
  dialog.add"Center", daysPanel );
  dialog.add"South", buttons );

  pack();
  setResizablefalse );
    }



    /**
     * Gets the selected day, as an <code>int</code>. Parses the text
     * of the selected label in the calendar to get the day.
     *
     @return the selected day or -1 if there is no day selected
     **/
    private int getSelectedDay()
    {
  if day == null )
      return -;
  try {
      return Integer.parseInt(day.getText());
  catch NumberFormatException e ) {
  }
  return -1;
    }



    /**
     * Sets the selected day. The day is specified as the label
     * control, in the calendar, corresponding to the day to select.
     *
     @param newDay day to select
     **/
    private void setSelectedJLabel newDay )
    {
  if day != null ) {
      day.setForegroundDAYS_FOREGROUND );
      day.setOpaquefalse );
      day.setBorderEMPTY_BORDER );
  }
  day = newDay;
  day.setForegroundSELECTED_DAY_FOREGROUND );
  day.setOpaquetrue );
  if daysGrid.hasFocus() )
      day.setBorderFOCUSED_BORDER );
    }



    /**
     * Sets the selected day. The day is specified as the number of
     * the day, in the month, to selected. The function compute the
     * corresponding control to select.
     *
     @param newDay day to select
     **/
    private void setSelectedint newDay )
    {
  setSelecteddays[(newDay+offset-1)/7+1][(newDay+offset-1)%7] );
    }



    /**
     * Updates the calendar. This function updates the calendar panel
     * to reflect the month and year selected. It keeps the same day
     * of the month that was selected, except if it is beyond the last
     * day of the month. In this case, the last day of the month is
     * selected.
     **/
    private void update()
    {
  int iday = getSelectedDay();
  for int i=0; i<7; i++ ) {
      days[1][i].setText" " );
      days[5][i].setText" " );
      days[6][i].setText" " );
  }
  calendar.setCalendar.DATE, );
  calendar.setCalendar.MONTH, month.getSelectedIndex()+Calendar.JANUARY );
  calendar.setCalendar.YEAR, year.getSelectedIndex()+FIRST_YEAR );

  offset = calendar.get(Calendar.DAY_OF_WEEK)-Calendar.SUNDAY;
  lastDay = calendar.getActualMaximum(Calendar.DATE);
  for int i=0; i<lastDay; i++ )
      days[(i+offset)/7+1][(i+offset)%7].setTextString.valueOf(i+1) );
  if iday != -) {
      if iday > lastDay )
    iday = lastDay;
      setSelectediday );
  }
    }



    /**
     * Called when the "Ok" button is pressed. Just sets a flag and
     * hides the dialog box.
     **/
    public void actionPerformedActionEvent e ) {
  if e.getSource() == ok )
      okClicked = true;
  hide();
    }

    /**
     * Called when the calendar gains the focus. Just re-sets the
     * selected day so that it is redrawn with the border that
     * indicate focus.
     **/
    public void focusGainedFocusEvent e ) {
  setSelectedday );
    }

    /**
     * Called when the calendar loses the focus. Just re-sets the
     * selected day so that it is redrawn without the border that
     * indicate focus.
     **/
    public void focusLostFocusEvent e ) {
  setSelectedday );
    }

    /**
     * Called when a new month or year is selected. Updates the calendar
     * to reflect the selection.
     **/
    public void itemStateChangedItemEvent e ) {
  update();
    }

    /**
     * Called when a key is pressed and the calendar has the
     * focus. Handles the arrow keys so that the user can select a day
     * using the keyboard.
     **/
    public void keyPressedKeyEvent e ) {
  int iday = getSelectedDay();
  switch e.getKeyCode() ) {
  case KeyEvent.VK_LEFT:
      if iday > )
    setSelectediday-);
      break;
  case KeyEvent.VK_RIGHT:
      if iday < lastDay )
    setSelectediday+);
      break;
  case KeyEvent.VK_UP:
      if iday > )
    setSelectediday-);
      break;
  case KeyEvent.VK_DOWN:
      if iday <= lastDay-)
    setSelectediday+);
      break;
  }
    }

    /**
     * Called when the mouse is clicked on a day in the
     * calendar. Selects the clicked day.
     **/
    public void mouseClickedMouseEvent e ) {
  JLabel day = (JLabel)e.getSource();
  if !day.getText().equals(" ") )
      setSelectedday );
  daysGrid.requestFocus();
    }

    public void keyReleasedKeyEvent e ) {}
    public void keyTypedKeyEvent e ) {}
    public void mouseEnteredMouseEvent e ) {}
    public void mouseExitedMouseEvent e) {}
    public void mousePressedMouseEvent e ) {}
    public void mouseReleasedMouseEvent e) {}



    /**
     * Constructs a new <code>DateChooser</code> with the given title.
     *
     @param owner owner dialog
     *
     @param title dialog title
     **/
    public DateChooserDialog owner, String title )
    {
  superowner, title, true );
  construct();
    }



    /**
     * Constructs a new <code>DateChooser</code>.
     *
     @param owner owner dialog
     **/
    public DateChooserDialog owner )
    {
  superowner, true );
  construct();
    }



    /**
     * Constructs a new <code>DateChooser</code> with the given title.
     *
     @param owner owner frame
     *
     @param title dialog title
     **/
    public DateChooserFrame owner, String title )
    {
  superowner, title, true );
  construct();
    }



    /**
     * Constructs a new <code>DateChooser</code>.
     *
     @param owner owner frame
     **/
    public DateChooserFrame owner )
    {
  superowner, true );
  construct();
    }



    /**
     * Selects a date. Displays the dialog box, with a given date as
     * the selected date, and allows the user select a new date.
     *
     @param date initial date
     *
     @return the new date selected or <code>null</code> if the user
     * press "Cancel" or closes the dialog box
     **/
    public Date selectDate date )
    {
  calendar.setTimedate );
  int _day = calendar.get(Calendar.DATE);
  int _month = calendar.get(Calendar.MONTH);
  int _year = calendar.get(Calendar.YEAR);

  year.setSelectedIndex_year-FIRST_YEAR );
  month.setSelectedIndex_month-Calendar.JANUARY );
  setSelected_day );
  okClicked = false;
  show();
  if !okClicked )
      return null;
  calendar.setCalendar.DATE, getSelectedDay() );
  calendar.setCalendar.MONTH, month.getSelectedIndex()+Calendar.JANUARY );
  calendar.setCalendar.YEAR, year.getSelectedIndex()+FIRST_YEAR );
  return calendar.getTime();
    }



    /**
     * Selects new date. Just calls {@link #select(Date)} with the
     * system date as the parameter.
     *
     @return the same as the function {@link #select(Date)}
     **/
    public Date select()
    {
  return select(new Date());
    }
}

   
    
    
  
Related examples in the same category
1. Vista Transparent DialogVista Transparent Dialog
2. Use this modal dialog to let the user choose one string from a long list
3. Tip Of Day Dialog
4. Swing error dialog (Exception dialog)Swing error dialog (Exception dialog)
5. Swing Login Domain Dialog with animationSwing Login Domain Dialog with animation
6. Shake a dialog
7. About dialog
8. Login DialogLogin Dialog
9. The base class for standard dialogs.
10. Password Dialog
11. A popup dialog with a message and a scrollable list of items
12. Dialog Panel
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.