swing calendar

hi,
  i have a date field..what i need it to do is when a button next to the field i  clicked, it opens up a  calendar,the user can then choose a date and on selection the input date  field gets that date value...

trance12Asked:
Who is Participating?
 
edwardiiiCommented:
Finally, add this class to the Class that you have your Calendar button on (in my case, the BlackBerry class).  This is the code that tells the PropertyChange event where to put the date your Calendar produces:

     public static void displayMessage(String dateChosen)
    {
        displayMessageResults = dateChosen;            
        stopDateJTextField.setText(displayMessageResults); // replace "stopDateJTextField" with your JTextField        
    }
0
 
objectsCommented:
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
trance12Author Commented:
second link doesnt work??
0
 
objectsCommented:
it does look like they are down, try again later should come back up
0
 
edwardiiiCommented:
Hi, trance12.  Below is code modified from that posted by GrandStrumpf some time ago.  Basically my BlackBerry class has a button "Select Date" by a JTextfield; when users click the button the calendar pops up, they click a date, and the value is sent back to the BlackBerry JTextfield.  I use a Property Change Listener to do this.

Code for the Calendar class (with its own helper classes):

     import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.*;

public class TemplateCal extends JFrame implements MouseListener
{
   
   JScrollPane scroll;
   JPanel p=new JPanel(new BorderLayout());  
     
  // Variables
  //--------------------------------------------
  private GregorianCalendar todayCalendar = new GregorianCalendar();
  private int currentYear   = todayCalendar.get(Calendar.YEAR);
  private int currentMonth  = todayCalendar.get(Calendar.MONTH);
  private int currentMonthStartWeekday;
  private int thisDay;

  // GUI fields
  //--------------------------------------------
  // Sub-JPanels
  private JPanel      yearJPanel       = new JPanel();
  private JPanel      monthJPanel      = new JPanel();
  private JPanel      dayJPanel        = new JPanel();
  private JPanel      bottomJPanel     = new JPanel();
  // Year
  private JLabel      yearJLabel       = new JLabel("8888", JLabel.CENTER);
  private JButton     yearMinusJButton = new JButton("<");
  private JButton     yearPlusJButton  = new JButton(">");
  // Month
  private JButton[]   monthJButtons    = new JButton[12];  
  // Day
  private JLabel[]    weekdayJLabels   = new JLabel[7];
  private JButton[]   dayJButtons      = new JButton[42];
  // Bottom
  private JButton     cancelJButton    = new JButton("Cancel");
  private JButton     todayJButton     = new JButton("Today");
  //private JButton todayJButton;  
 
  // Action Listeners
  //--------------------------------------------
  private ActionListener yearListener   = new YearListener();
  private ActionListener monthListener  = new MonthListener();
  private ActionListener dayListener    = new DayListener();
  private ActionListener JButtonListener = new JButtonListener();
 
  private Color metalCopy;
  private Color keepColor;
  private Color keepForeground;
  private Font  keepFont;
  private Font bigFont = new Font("Arial", 1, 12);  
 
  // Update the chooser with the new View
  //--------------------------------------------
  private void updateView() {

    getRootPane().setDefaultButton(todayJButton);
    Color origColor = cancelJButton.getBackground();
    metalCopy = new Color (223,245,247);
     
    // Year
    yearJLabel.setText("" + currentYear);
   
    // Months
    for (int cnt = 0; cnt < monthJButtons.length; cnt++)
    {
     
      monthJButtons[cnt].addMouseListener(this);
      if (cnt == currentMonth)
      {
        //monthJButtons[cnt].setBackground(Color.CYAN);
        monthJButtons[cnt].setForeground(Color.blue);
        monthJButtons[cnt].setBorderPainted(false);
        monthJButtons[cnt].setBackground(metalCopy);
        monthJButtons[cnt].setFont(new java.awt.Font("Arial", 1, 12));
       
      } else
      {
        monthJButtons[cnt].setBackground(origColor);
        monthJButtons[cnt].setForeground(Color.black);
        monthJButtons[cnt].setBorderPainted(true);
      }
    }
   
    // Days
    GregorianCalendar tempCal = new GregorianCalendar(currentYear, currentMonth, 1);
    currentMonthStartWeekday = tempCal.get(Calendar.DAY_OF_WEEK);
   
    for (int cnt = 0; cnt < dayJButtons.length; cnt++)
    {
     
      dayJButtons[cnt].addMouseListener(this);
      // Disable JButtons preceding start of month
      if (cnt < currentMonthStartWeekday - 1)
      {
        dayJButtons[cnt].setBackground(origColor );
        dayJButtons[cnt].setText("");
        dayJButtons[cnt].setEnabled(false);        
        continue;
      }
      // Populate dates on JButtons
      if (tempCal.get(Calendar.MONTH) == currentMonth)
      {
        dayJButtons[cnt].setEnabled(true);
        dayJButtons[cnt].setText("" + tempCal.get(Calendar.DATE));
       
        if (tempCal.get(Calendar.DATE)  == todayCalendar.get(Calendar.DATE)
         && tempCal.get(Calendar.MONTH) == todayCalendar.get(Calendar.MONTH)
         && tempCal.get(Calendar.YEAR)  == todayCalendar.get(Calendar.YEAR))
        {
          dayJButtons[cnt].setForeground(Color.blue);
          dayJButtons[cnt].setBackground(metalCopy);
          dayJButtons[cnt].setFont(new java.awt.Font("Arial", 1, 12));
          dayJButtons[cnt].setBorderPainted(false);
          //dayJButtons[cnt].setBackground(new javax.swing.plaf.ColorUIResource(0,0,0));
          //dayJButtons[cnt].setContentAreaFilled(false);  //hides the button shape, so you can use image
          dayJButtons[cnt].setText("" + tempCal.get(Calendar.DATE));          
          thisDay = tempCal.get(Calendar.DATE);
        }
        else
        {
          dayJButtons[cnt].setBackground(origColor );
          dayJButtons[cnt].setForeground(Color.black );          
        }
        tempCal.add(Calendar.DATE, 1);        
        continue;
      }
      // Disable JButtons following end of month
      dayJButtons[cnt].setBackground(origColor );
      dayJButtons[cnt].setText("");
      dayJButtons[cnt].setEnabled(false);
    }
   
  }

  // Constructor
  //--------------------------------------------
  public TemplateCal()
  {
    getRootPane().setDefaultButton(todayJButton);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Building JPanel for years
    //+++++++++++++++++++++++++++++++++++++++++++++
    yearJPanel.setLayout(new java.awt.FlowLayout());    
    yearJPanel.add(yearMinusJButton);
    yearMinusJButton.setFocusPainted(false);
    yearMinusJButton.setDefaultCapable(false);
    yearJPanel.add(yearJLabel);
    yearJPanel.add(yearPlusJButton);  
   
    yearMinusJButton.addActionListener(yearListener);
    yearMinusJButton.addMouseListener(this);
    yearPlusJButton.addActionListener(yearListener);
    yearPlusJButton.addMouseListener(this);
   
       
    // Building JPanel for months
    //+++++++++++++++++++++++++++++++++++++++++++++
    monthJPanel.setLayout(new java.awt.GridBagLayout());
    GridBagConstraints monthConstraints = new GridBagConstraints();
    monthConstraints.gridx=0;
    monthConstraints.fill=GridBagConstraints.HORIZONTAL;
    monthConstraints.weightx=0;
    monthConstraints.weighty=0;
   
    monthJButtons[0]  = new JButton("Jan");
    monthJButtons[1]  = new JButton("Feb");
    monthJButtons[2]  = new JButton("Mar");
    monthJButtons[3]  = new JButton("Apr");
    monthJButtons[4]  = new JButton("May");
    monthJButtons[5]  = new JButton("Jun");
    monthJButtons[6]  = new JButton("Jul");
    monthJButtons[7]  = new JButton("Aug");
    monthJButtons[8]  = new JButton("Sep");
    monthJButtons[9]  = new JButton("Oct");
    monthJButtons[10] = new JButton("Nov");
    monthJButtons[11] = new JButton("Dec");
   
    for(int month = 0; month < 12; month++)
    {      
      if(month <= 5)
      {
        monthConstraints.gridy = 0;
        monthConstraints.gridx = month + 1;
        monthJButtons[month].setPreferredSize(new Dimension(57, 25));
        monthJButtons[month].setMaximumSize(new java.awt.Dimension(57, 25));
        monthJButtons[month].setMinimumSize(new java.awt.Dimension(57, 25));
        monthJPanel.add(monthJButtons[month],monthConstraints);
      }
      else
      {    
        monthConstraints.gridy = 1;
        monthConstraints.gridx = (month-6) + 1;
        monthJButtons[month].setPreferredSize(new Dimension(57, 25));
        monthJButtons[month].setMaximumSize(new java.awt.Dimension(57, 25));
        monthJButtons[month].setMinimumSize(new java.awt.Dimension(57, 25));
        monthJPanel.add(monthJButtons[month],monthConstraints);
      }
      monthJButtons[month].addActionListener(monthListener);
    }
   
    // Building JPanel for days
    //+++++++++++++++++++++++++++++++++++++++++++++
    dayJPanel.setLayout(new java.awt.GridLayout(0,7));    
    weekdayJLabels[0] = new JLabel("S", JLabel.CENTER);
    weekdayJLabels[1] = new JLabel("M", JLabel.CENTER);
    weekdayJLabels[2] = new JLabel("T", JLabel.CENTER);
    weekdayJLabels[3] = new JLabel("W", JLabel.CENTER);
    weekdayJLabels[4] = new JLabel("T", JLabel.CENTER);
    weekdayJLabels[5] = new JLabel("F", JLabel.CENTER);
    weekdayJLabels[6] = new JLabel("S", JLabel.CENTER);
    for(int day = 0; day < 7; day++) {
      dayJPanel.add(weekdayJLabels[day]);
    }
    // JButtons for days
    for(int cnt = 0; cnt < dayJButtons.length; cnt++) {
      //dayJButtons[cnt] = new JButton("" + cnt);
      dayJButtons[cnt] = new JButton("" + cnt);
      dayJPanel.add(dayJButtons[cnt]);
      dayJButtons[cnt].addActionListener(dayListener);
    }
   
    // Building JPanel for bottom JButtons
    //+++++++++++++++++++++++++++++++++++++++++++++
    bottomJPanel.setLayout(new java.awt.BorderLayout());
    {
      JPanel alignJPanel = new JPanel();
      alignJPanel.setLayout(new java.awt.GridLayout(1,0));
      alignJPanel.add(cancelJButton);
      cancelJButton.addMouseListener(this);
      alignJPanel.add(todayJButton);
      todayJButton.addMouseListener(this);
      todayJButton.setFocusPainted(true);            
     
      bottomJPanel.add(alignJPanel, java.awt.BorderLayout.CENTER);
      cancelJButton.addActionListener(JButtonListener);      
      todayJButton.addActionListener(JButtonListener);            
     
    }
   
    this.getContentPane().setLayout(new GridBagLayout());
    GridBagConstraints myConstraints = new GridBagConstraints();
    myConstraints.gridx = 0;
    myConstraints.fill = GridBagConstraints.NONE;
    myConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
   
    myConstraints.gridy = 0;
    this.getContentPane().add(yearJPanel, myConstraints);
    myConstraints.gridy = 1;
    this.getContentPane().add(monthJPanel, myConstraints);
    myConstraints.gridy = 2;
    this.getContentPane().add(dayJPanel, myConstraints);
    myConstraints.gridy = 3;    
    this.getContentPane().add(bottomJPanel, myConstraints);      
    this.setSize(350,375);    
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);    
    this.setTitle("Calendar");
    this.setLocation(550, 180);    
       
    // Call the update view method
    //+++++++++++++++++++++++++++++++++++++++++++++
    this.updateView();
           
  }
 
  // Main Method
  //--------------------------------------------
  public static void main(final String[] args) {
   
    new TemplateCal().setVisible(true);
   
  }
 
  public void paintBorder(MouseEvent e, boolean borderPainted, Color buttonColor, Color buttonTextColor, Font textFont)
  {
        Object source = e.getSource();
        if (source instanceof JButton)
        {
             Color initColor = ((JButton)source).getBackground();    
             Color initForeground = ((JButton)source).getForeground();
             Font initFont = ((JButton)source).getFont();
         
             if (!(initColor == Color.gray))
             {
                  keepColor = initColor;
                  keepForeground = initForeground;
                  keepFont = initFont;
             }    
             
       ((JButton)source).setBackground(buttonColor);
       ((JButton)source).setBorderPainted(borderPainted);
       ((JButton)source).setForeground(buttonTextColor);
       ((JButton)source).setFont(textFont);
        }
   }
   
   
  public void mouseEntered(MouseEvent e)
  {      
      paintBorder(e, false, Color.gray, Color.yellow, bigFont);      
  }
 
  public void mouseExited(MouseEvent e)
  {
      paintBorder(e, true, keepColor ,keepForeground,keepFont);
  }
 
  public void mouseClicked(MouseEvent e) {
  }
 
  public void mousePressed(MouseEvent e) {
  }
 
  public void mouseReleased(MouseEvent e)
  {
     
  }
 
  class YearListener implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      Object buttonPressed = e.getSource();
      if (buttonPressed == yearMinusJButton) {
        currentYear--;
      }
      else if (buttonPressed == yearPlusJButton) {
        currentYear++;
      }
      updateView();
    }
  }
  class MonthListener implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      Object buttonPressed = e.getSource();
      for (int cnt = 0; cnt < monthJButtons.length; cnt++) {
        if (buttonPressed == monthJButtons[cnt]) {
          currentMonth = cnt;
          break;
        }
      }
      updateView();
    }
  }
  class DayListener implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      Object buttonPressed = e.getSource();
      for (int cnt = 0; cnt < dayJButtons.length; cnt++) {
        if (buttonPressed == dayJButtons[cnt]) {
          String datePicked = "" + (currentMonth+1) + "/" + ((cnt+1) - (currentMonthStartWeekday-1)) + "/" + currentYear;          
          //System.out.println(message);
          String dateChosen = datePicked;
          //BlackBerry.displayMessage(nameOfCourse);
          firePropertyChange("selectedDate",null,dateChosen);
          break;
        }
      }
    }
  }  
 
 
  class JButtonListener implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      Object buttonPressed = e.getSource();      
     
      if (buttonPressed == todayJButton)
      {
        //the line below would allow someone to select some other month and year
        //and press the Today JButton and get incorrect results, e.g. 12/30/2021
       
        //String datePicked = (currentMonth+1) + "/" + thisDay + "/" + currentYear;
       
        String datePicked = (todayCalendar.get(Calendar.MONTH)+1) + "/" + thisDay + "/" + todayCalendar.get(Calendar.YEAR);
        String dateChosen = datePicked;
        firePropertyChange("selectedDate",null,dateChosen);          
      }  
     
      else if (buttonPressed == cancelJButton)
      {
        String dateChosen = "";
        firePropertyChange("cancelDate",null,dateChosen);
      }            
         
    }
  }  
}

               
class MyPanel extends JPanel
{
    int paintX=0;
    int paintY=0;
    public MyPanel()
    {
        super();
        setOpaque(true);
    }
    public void paint(Graphics g)
    {
        super.paint(g);
    }
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);      
    }  

}
0
 
edwardiiiCommented:
Here is the code in the BlackBerry class button "Select Date":

     final TemplateCal newTemplateCal = new TemplateCal();    
     newTemplateCal.setVisible(true);    
     setEnabled(false);    
     
    newTemplateCal.addWindowListener(new java.awt.event.WindowAdapter()
    {
        public void windowClosed(WindowEvent e)
        {
            setEnabled(true);
        }
    });            
     
   newTemplateCal.addPropertyChangeListener(
         new PropertyChangeListener()
         {

             public void propertyChange(PropertyChangeEvent evt)
             {
                 if(evt.getPropertyName().equals("selectedDate") )
                 {
                    newTemplateCal.dispose();  //tears down the Calendar so user sees a re-enabled BlackBerry instance
                    setVisible(true);  //have to do this to get the running BlackBerry instance to have the focus
                                             , otherwise the user has to click the form                    
                    BlackBerry.displayMessage((String)evt.getNewValue());
                 }
                 
                 else if(evt.getPropertyName().equals("cancelDate") )
                 {
                    newTemplateCal.dispose();
                    setVisible(true);
                    stopDateJTextField.requestFocus();                    
                   
                 }
                 
             }
     });
0
 
edwardiiiCommented:
Sorry--please delete the MyPanel code at the end of the TemplateCal/Calendar code; I was testing something:

class MyPanel extends JPanel
{
    int paintX=0;
    int paintY=0;
    public MyPanel()
    {
        super();
        setOpaque(true);
    }
    public void paint(Graphics g)
    {
        super.paint(g);
    }
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);      
    }  

}
0
 
trance12Author Commented:
thanks..but where is the action listener for the button...?..what is the button supposed to invoke?
0
 
edwardiiiCommented:
Thanks for accepting.  I apologize for not being more clear.  The code for the Calendar button's ActionListener is:

    calendarJButton.setText("Select Date");
        calendarJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calendarJButtonActionPerformed(evt);
            }
        });

Also, my second post (9:01 am today) was the body of the calendarJButtonActionPeformed event.  I should have prefaced that block of code with:

     private void calendarJButtonActionPerformed(java.awt.event.ActionEvent evt) {

I'll loath to submit the entire code of my BlackBerry class (which houses the Calendar button), but if it will help make the interactions between the two classes (BlackBerry and TemplateCal), just say the word.  To answer your second question, the calendarJButton instantiates the TemplateCal class, which is a calendar.  See this EE post for an explanation of how the PropertyChangeEvent works:

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21255771.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.