The Artima Developer Community
Sponsored Link

Java Answers Forum
calander

1 reply on 1 page. Most recent reply: May 17, 2003 2:51 PM by Charles Bell

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
gurdip sidhu

Posts: 2
Nickname: sid
Registered: May, 2003

calander Posted: May 15, 2003 4:11 AM
Reply to this message Reply
Advertisement
Can anyone help me. I need to display a calander in my application for the current month and allowing a user to navigate backwards or forwards by a month?????


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: calander Posted: May 17, 2003 2:51 PM
Reply to this message Reply
/*   DateSelector.java
 *   May 17, 2003
 *   Copyright (C) 2003 QuantumHyperSpace
 *   www.quantumhyperspace.com
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.text.*;
 
/** DateSelector provides a graphical user interface 
 *  for selection of a Date from a calendar. A calendar 
 *  is displayed for the current month. The user can 
 *  move the current month forward or in reverse. The 
 *  calling class should use the mthod getDate() or 
 *  getCalendar() to obtain a date. These methods will 
 *  wait until a date selection is confirmed. The 
 *  calling class can either use the Date or Gregoriran 
 *  Calendar object directly or request various string 
 *  or int value options of the selected month, day of 
 *  month, and year. A DateSelector can be initialized 
 *  with an optional string message. 
 *  How to use this class:
 *      DateSelector dateSelector = new DateSelector("Pick a Date");
 *      Date date = dateSelector.getDate();
 *   or
 *      Calendar calendar = dateSelector.getGregorianCalendar();
 *   or 
 *      Date date = new DateSelector("Select a Date").getDate();
 *   or 
 *      String message = "Select the Date you want to leave";
 *      Calendar calendar = new DateSelector(message).getGregorianCalendar();
 *
 *  @author Charles Bell
 *  @version May 17, 2003
 */
public class DateSelector extends JFrame implements ActionListener{
	
    private final String[] months = {"January","February",
            "March","April","May","June","July","August",
            "September","October","November","December"};
 
    private final String[] weekdays = {"Sunday","Monday",
            "Tuesday","Wednesday","Thursday","Friday","Saturday"};
 
    private boolean debug = false;
    private JLabel monthLabel; 
    private JLabel yearLabel; 
    private JPanel calendarPanel;
    private Font titleFont = new Font("SansSerif",Font.BOLD,20);
 
    protected int selectedDay = -1;
    protected int month = -1;
    protected int year = -1;
    protected String dateSelection = "";
    private String message = "";
    private boolean dateSelected = false;
 
    
    /**	Constructs a DateSelector.
    */
    public DateSelector(){
        super("Select a Date");
        init();
    }
    
    /**	Constructs a DateSelector using the string message.
    */
    public DateSelector(String message){
        super(message);
        init();
    }
 
    /**	Runs this as a demonstration application.
    */
    public static void main(String[] args){
        DateSelector dateSelector = new DateSelector("Select a Date");
        Date date = dateSelector.getDate();
        if (date != null){
            System.out.println("You selected " + DateFormat.getDateInstance().format(date));
            System.out.println("You selected " + DateFormat.getDateInstance().format(date));
            System.out.println("You selected " + dateSelector.getDateSelection());
            System.out.println("You selected year " + dateSelector.getYearSelection());
            System.out.println("You selected the month of " + dateSelector.getMonthSelection());
            System.out.println("Your selected day of week " + dateSelector.getSelectedDayOfWeek());
            System.out.println("Your selected day of month " + dateSelector.getDayOfMonthSelection());
            System.out.println("Your selected year number " + dateSelector.getSelectedYear());
            System.out.println("Your selected month index " + dateSelector.getSelectedMonth());
            System.out.println("Your selected day number " + dateSelector.getSelectedDay());
        }
        Calendar calendar = dateSelector.getGregorianCalendar();
        if (calendar != null){
            if (dateSelector.isOnWeekend(calendar)){
                System.out.println("Your selected date is on the week end.");
            }else{
                System.out.println("Your selected date is not on a week end.");
            }
            System.out.println("Era: " + calendar.get(Calendar.ERA));
            System.out.println("Year: " + calendar.get(Calendar.YEAR));
            System.out.println("Month index: " + calendar.get(Calendar.MONTH));
            System.out.println("Week of Year: " + calendar.get(Calendar.WEEK_OF_YEAR));
            System.out.println("Week of month: " + calendar.get(Calendar.WEEK_OF_MONTH));
            System.out.println("Date: " + calendar.get(Calendar.DATE));
            System.out.println("Day of month: " + calendar.get(Calendar.DAY_OF_MONTH));
            System.out.println("Day of month: " + calendar.get(Calendar.DAY_OF_YEAR));
            System.out.println("Day of week: " + calendar.get(Calendar.DAY_OF_WEEK));
            System.out.println("Day of week in month: "
                + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
        }else{
            System.out.println("No date was selected.");
        }
        System.exit(0);
        
    }
 
    /**	Initializes the graphical user interface. Sets up JPanel
     *	components to hold the "Prev" and "Next" buttons used to 
     *	move the desired month forward or reverse. Starts with 
     *	the current month. The column titles are added for each 
     *	day of the week.
     */
    public void init(){
        GregorianCalendar today = new GregorianCalendar();
        month = today.get(Calendar.MONTH);
        year = today.get(Calendar.YEAR);
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
 
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new GridLayout(3,1));
        JPanel top = new JPanel();
        JButton prevMonthButton = new JButton("Prev");
        JButton nextMonthButton = new JButton("Next");
        prevMonthButton.addActionListener(this);
        nextMonthButton.addActionListener(this);
        top.add(prevMonthButton);
        top.add(nextMonthButton);
 
        JPanel middle = new JPanel();
        monthLabel = new JLabel();
        yearLabel = new JLabel();
        monthLabel.setFont(titleFont); 
        yearLabel.setFont(titleFont); 
        middle.add(monthLabel);
        middle.add(new JLabel(" "));
        middle.add(yearLabel);
 
        JPanel bottom = new JPanel();
        bottom.setLayout(new GridLayout(1,7,5,5));
 
        bottom.add(new JLabel("Sun",SwingConstants.CENTER));
        bottom.add(new JLabel("Mon",SwingConstants.CENTER));
        bottom.add(new JLabel("Tue",SwingConstants.CENTER));
        bottom.add(new JLabel("Wed",SwingConstants.CENTER));
        bottom.add(new JLabel("Thu",SwingConstants.CENTER));
        bottom.add(new JLabel("Fri",SwingConstants.CENTER));
        bottom.add(new JLabel("Sat",SwingConstants.CENTER));
        controlPanel.add(top);
        controlPanel.add(middle);
        controlPanel.add(bottom);
 
        getContentPane().add(controlPanel,"North");
 
        calendarPanel = new JPanel();
        getContentPane().add(calendarPanel,"Center");
        updateCalendarDisplay(month, year);
        setLocationRelativeTo(null);
        pack();
        show();
    }
    
    /** Waits until a date is selected then returns
     *  the selected date as a Date object.
     *  Returns null if no date is selected.
     */
    public Date getDate(){
        Date date = null;
        while ((!dateSelected) && (isVisible())){
            try{
                Thread.sleep(100);
            }catch(InterruptedException ie){
                System.err.println("Sleep thread interrupted.");
            }
        }
        if (dateSelected) date = new GregorianCalendar(year, month, selectedDay).getTime();
        return date;
    }
    
    /** Waits until a date is selected then returns the 
     *  selected date as a GregorianCalendar object.
     *  Returns null if no date is selected.
     */
    public GregorianCalendar getGregorianCalendar(){
        GregorianCalendar calendar = null;
        while ((!dateSelected) && (isVisible())){
            try{
                Thread.sleep(100);
            }catch(InterruptedException ie){
                System.err.println("Sleep thread interrupted.");
            }
        }
        if (dateSelected) calendar = new GregorianCalendar(year, month, selectedDay);
        return calendar;
    }
    
	
    /**	Updates the calendar display according to the input month and year.
     *	The Calendar title is updated with the string value of the month 
     *	and year. A placeholder JButton is inserted into the columns not 
     *	used for the first and last week of the month. The gridlayout 
     *	changes depending on the number of weeks in the month.
     *	A JButton is added for each day of the month.
     */
    public void updateCalendarDisplay(int month, int year){
        if (debug) System.out.println("Debug:  Month: " + month + " Year: " + year);
        monthLabel.setText(months[month]); 
        yearLabel.setText(String.valueOf(year)); 
        calendarPanel.removeAll();
        GregorianCalendar today = new GregorianCalendar();
        GregorianCalendar firstDayOfMonth = new GregorianCalendar(year,month,1);
        GregorianCalendar lastDayOfMonth = new GregorianCalendar(year,month,firstDayOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
        int weeksInMonth = lastDayOfMonth.get(Calendar.WEEK_OF_MONTH);
        if (debug) System.out.println("Debug:  weeksInMonth: " + weeksInMonth);
        calendarPanel.setLayout(new GridLayout(weeksInMonth,7,3,3));
        int firstDayInFirstWeek = firstDayOfMonth.get(Calendar.DAY_OF_WEEK);
        if (debug) System.out.println("Debug:  firstDayInFirstWeek: " + firstDayInFirstWeek);
        for (int i = 1;i<firstDayInFirstWeek;i++){
            JButton blank = new JButton("--");
            blank.setEnabled(false);
            calendarPanel.add(blank);
        }
        /* Since the roll function starts over, 
         * have to do all but the last day 
         * and do last day outside of for loop.
         */
        for (GregorianCalendar currentDay = firstDayOfMonth;!currentDay.equals(lastDayOfMonth) ;currentDay.roll(Calendar.DAY_OF_MONTH,1)){
            JButton nextButton = new JButton(String.valueOf(currentDay.get(Calendar.DAY_OF_MONTH)));
            if (isOnWeekend(currentDay)) nextButton.setForeground(Color.blue);
            if (compare(currentDay,today)) nextButton.setForeground(Color.red);
            nextButton.addActionListener(this);
            calendarPanel.add(nextButton);
        }
        /* Now do the last day of the month. */
        JButton lastDayButton = new JButton(String.valueOf(lastDayOfMonth.get(Calendar.DAY_OF_MONTH)));
        if (isOnWeekend(lastDayOfMonth)) lastDayButton.setForeground(Color.blue);
        if (compare(lastDayOfMonth,today)) lastDayButton.setForeground(Color.red);
        lastDayButton.addActionListener(this);
        calendarPanel.add(lastDayButton);
        int lastDayInLastWeek = lastDayOfMonth.get(Calendar.DAY_OF_WEEK);
        if (debug) System.out.println("Debug: lastDayInLastWeek: " + lastDayInLastWeek);
        for (int i = lastDayInLastWeek+1;i<=7;i++){
            JButton blank = new JButton("--");
            blank.setEnabled(false);
            calendarPanel.add(blank);
        }
        calendarPanel.validate();
        pack();
    }
 
    /**	Implements ActionListener interface. Responds to Previous 	
    *	and Next button commands. Responds to day of month selection 
    *	which ends Thread execution. The user can either move the 
    *	month selection forward or in reverse. Once a day is selected
    *	and confirmed the thread stops and the frame is hidden.
    *	The calling program can request the selected date using any
    *	of several options.
    */
    public void actionPerformed(ActionEvent actionevent){
        String actionString = actionevent.getActionCommand();
        if (debug) System.out.println("Debug: actionString: " + actionString);
        if (actionString.compareTo("Prev") == 0) {
            month = month - 1;
            if (month < 0){
                month = 11;
                year = year - 1;
            }
            updateCalendarDisplay(month,year);
        }else if (actionString.compareTo("Next") == 0) {
            month = month + 1;
            if (month == 12){
                month = 0;
                year = year + 1;
            }
            updateCalendarDisplay(month,year);
        }else{
            if (getInt(actionString) > 0) {
                selectedDay = getInt(actionString);
                dateSelection = String.valueOf(month + 1) + "-" + String.valueOf(selectedDay) + "-" + String.valueOf(year);
                if (debug) System.out.println("Debug: Date Selection : " + dateSelection);
                if (debug) System.out.println("Debug: Month: " + String.valueOf(month) + " Day: " + actionString + " Year: " + String.valueOf(year));
            }
            if (confirmSelection()) {
                hide();
                dateSelected = true;
            }
        }
    }
 
    /**	Returns the selected date string in format 
     *  month-day-year.
     *	eg: 2-16-2002
     */
    public String getDateSelection(){
        return dateSelection;
    }
 
    /**	Returns the selected date string in format 
     *  monthstring daystring, yearstring
     *	eg: February 16, 2002
     */
    public String getSelectionString(){
        return getMonthSelection() + " " 
            + getDayOfMonthSelection()
            + ", " + getYearSelection();
    }
 
    /**	Returns the selected month value 
     *  or -1 if no date has been selected.
     *	January corresponds to 0;
     *	December corresponds to 11;
     */
    public int getSelectedMonth(){
        return month;
    }
 
    /**	Returns the selected month value. 
     *	January corresponds to months[0];
     *	December corresponds to months[11];
     */
    public String getMonthSelection(){
        return months[month];
    }
 
    /**	Returns the selected day value starting with 1
     *  or -1 if no date has been selected.
     */
    public int getSelectedDay(){
        return selectedDay;
    }
    
    /**	Returns the selected day of week string.
     */
    public String getSelectedDayOfWeek(){
        return weekdays[new GregorianCalendar(year, month, selectedDay).get(Calendar.DAY_OF_WEEK)-1];
    }
 
    /**	Returns the selected day string starting with 1.
     */
    public String getDayOfMonthSelection(){
        return String.valueOf(selectedDay);
    }
 
    /**	Returns the selected 4 digit year value 
     *  or -1 if no date has been selected.
     */
    public int getSelectedYear(){
        return year;
    }
 
    /**	Returns the selected 4 digit year string.
     */
    public String getYearSelection(){
        return String.valueOf(year);
    }
 
    /**	Converts the input string into an integer. 
     *  Returns -1 of unsuccessful.
     */
    private int getInt(String s){
        int n = -1;
        try{
            n = Integer.parseInt(s);
        }catch(NumberFormatException nfe){
            n = -1;
            System.err.println("NumberFormatException: " + nfe.getMessage());
        }
        return n;
    }
 
    /**	Determines if the input Calendar object 
     *  corresponds to either a Saturday or Sunday.
     */
    public boolean isOnWeekend(Calendar calendar){
        return ((calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) ||
                (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY));
    }
 
    /**	Converts the input string into an integer. 
     *  Returns -1 of unsuccessful.
     */
    private boolean compare(GregorianCalendar first, GregorianCalendar second){
        return ((first.get(Calendar.DAY_OF_MONTH) == second.get(Calendar.DAY_OF_MONTH))
                && (first.get(Calendar.MONTH) == second.get(Calendar.MONTH))
                && (first.get(Calendar.YEAR) == second.get(Calendar.YEAR)));
    }
 
    /**	Confirms the date selection using a 
     *  JOptionPane ConfirmDialog.
     */
    public boolean confirmSelection(){
        return (JOptionPane.showConfirmDialog(null,"Select " + getSelectionString() + "?", "Select " + getSelectionString() + "?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION);
    }
}
 

Flat View: This topic has 1 reply on 1 page
Topic: how to know the JVM version thru a program, Previous Topic   Next Topic Topic: Little help with a for loop inside a for loop

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use