Solved

Help Customize/Modify this DateChooser class

Posted on 2007-03-26
11
340 Views
Last Modified: 2008-02-01
I've been using this code to create a GUI Date Chooser with a pop-up calendar and need some help customizing it.  There's two parts to the DateChooser:

1. TextBox that displays the date selected
2. Button to open the pop-up calendar to select a date

How can I modify this code (or the code I use to create/initialize my DateChooser) so that I can specify the width of each of those components?  Right now all I can do is specify the total height/width and location.

Here is what I use to create a DateChooser:

objDC = new DateChooser();
getContentPane().add(objDC);
objDC.setBounds(30, 110, 140, 20);
objDC.setEditable(false);



Here is the DateChooser class (that I found somewhere on the internet awhile ago):

/*
 * @(#)JDateChooser.java      1.000 September 24, 2002
 *
 */
import java.beans.*;
import java.util.*;
import java.text.SimpleDateFormat;

import java.awt.*;
import java.awt.event.*;

import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

import javax.swing.*;
import javax.swing.event.*;
//import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.border.*;

import javax.accessibility.*;

/**
 * A component that combines a text field and a popup calendar.
 * The user can select a date from the popup calendar, which appears at the
 * user's request. If you make the date chooser editable, then the date chooser
 * includes an editable field into which the user can type a value.
 *
 * <strong>Warning:</strong>
 * Serialized objects of this class will not be compatible with
 * future Swing releases. The current serialization support is
 * appropriate for short term storage or RMI between applications running
 * the same version of Swing.  As of 1.4, support for long term storage
 * of all JavaBeans<sup><font size="-2">TM</font></sup>
 * has been added to the <code>java.beans</code> package.
 * Please see {@link java.beans.XMLEncoder}.
 *
 * @beaninfo
 *   attribute: isContainer false
 * description: A combination of a text field and a popup calendar.
 */

public class DateChooser extends JComponent implements Serializable, ActionListener, MouseListener{
      /*
      * Flag which determines wether or not the text field is editable
      *
      * @see #isEditable
      * @see #setEditable
      */
      private boolean isEditable = false;

      /*
      * The rate at which the user scrolls through the months on the popup
      * calendar when the arrow button at the top of the popup calendar are
      * held down.  Units are in months per second.
      *
      * @see #getMonthScrollRate
      * @see #setMonthScrollRate
      */
      private int monthScrollRate = 5;

      /*
      * The date which the user has selected.  Return null of the user chose
      * "NONE".
      *
      * @see #getDate
      * @see #setDate
      */
      private Date selectedDate;

      /*
      * The format in which the selected date will appear in the text field.
      *
      * @see #getDateFormat
      * @see #setDateFormat
      * @see #getDateFormatPattern
      * @see #setDateFormatPattern
      */
      private SimpleDateFormat returnDateFormatter = new SimpleDateFormat("MMM dd, yyyy");

      /*
      * Other non-accesored variables
      */
      private JTextField componentTextField;
      private JButton componentButton;
      private int componentMargin = 2;
      private JDialog popupCalendar;
      private JButton todayButton, noneButton;
      private JButton prevButton, nextButton;
      private javax.swing.Timer nextMonthTimer, prevMonthTimer;
      private JLabel monthButton;
      private SimpleDateFormat monthyearFormatter = new SimpleDateFormat("MMMM yyyy");
      private JPanel dayHeaderPanel, dayPanel;
      private JLabel[] dayLabel = new JLabel[42];
      private Date todaysDate, displayedDate;
      private GregorianCalendar displayedCalendar, todaysCalendar, selectedCalendar;
      public int todaysYear, todaysMonth, todaysDay, selectedYear, selectedMonth, selectedDay;
      private HashMap dayMap = new HashMap();
      private HashMap monthMap = new HashMap();



///////////////////
// Constructors
///////////////////

      /*
      * Creates a <code>DateChooser</code> with no initial date.
      */
      public DateChooser() {

            layoutControl();
            layoutCalendarWindow();
      }

      /*
      * Creates a <code>DateChooser</code> with a text field containing
      * the specified number of columns.
      *
      * @param cols the number of columns in the text field
      */
      public DateChooser(int cols) {

            layoutControl();
            layoutCalendarWindow();
            componentTextField.setColumns(cols);
      }

      /*
      * Creates a <code>DateChooser</code> with a specified initially
      * selected date.
      *
      * @param aDate the date which is initially selected and appears
      * in the text field
      */
      public DateChooser(Date aDate) {

            layoutControl();
            layoutCalendarWindow();

            selectedDate = aDate;
            selectedCalendar.setTime(selectedDate);
            selectedYear = selectedCalendar.get(Calendar.YEAR);
            selectedMonth = selectedCalendar.get(Calendar.MONTH);
            selectedDay = selectedCalendar.get(Calendar.DAY_OF_MONTH);
            displayedDate = aDate;
            displayedCalendar.setTime(displayedDate);
            updateCalendarDisplay();
            componentTextField.setText(returnDateFormatter.format(selectedDate));
            
      }

      /*
      * Creates a <code>DateChooser</code> with a specified initially
      * selected date and a text field containing the specified number
      * of columns.
      *
      * @param aDate the date which is initially selected and appears
      * in the text field
      * @param cols the number of columns in the text field
      */
      public DateChooser(Date aDate, int cols) {

            layoutControl();
            layoutCalendarWindow();

            selectedDate = aDate;
            selectedCalendar.setTime(selectedDate);
            selectedYear = selectedCalendar.get(Calendar.YEAR);
            selectedMonth = selectedCalendar.get(Calendar.MONTH);
            selectedDay = selectedCalendar.get(Calendar.DAY_OF_MONTH);
            displayedDate = aDate;
            displayedCalendar.setTime(displayedDate);
            updateCalendarDisplay();
            componentTextField.setText(returnDateFormatter.format(selectedDate));
            componentTextField.setColumns(cols);
            
      }

///////////////////
// Public Methods
///////////////////

      public Date getDate() {
            return selectedDate;
      }

      public SimpleDateFormat getDateFormat() {
            return returnDateFormatter;
      }

      public String getDateFormatPattern() {
            String myPattern = returnDateFormatter.toPattern();
            return myPattern;
      }

      public int getMonthScrollRate() {
            return monthScrollRate;
      }

      public Font getPopupFont() {
            Font myFont = monthButton.getFont();
            return myFont;
      }

      public Font getTextFont() {
            Font myFont = componentTextField.getFont();
            return myFont;
      }

      public boolean isEditable() {
            return isEditable;
      }

      public void setDate(Date myDate) {
            selectedDate = myDate;
            selectedCalendar.setTime(selectedDate);
            selectedYear = selectedCalendar.get(Calendar.YEAR);
            selectedMonth = selectedCalendar.get(Calendar.MONTH);
            selectedDay = selectedCalendar.get(Calendar.DAY_OF_MONTH);
            componentTextField.setText(returnDateFormatter.format(selectedDate));
            displayedCalendar.setTime(selectedDate);
            updateCalendarDisplay();
      }

      public void setDateFormat(SimpleDateFormat mySimpleFormat) {
            returnDateFormatter = mySimpleFormat;
      }

      public void setDateFormatPattern(String pattern) {
            returnDateFormatter.applyPattern(pattern);
      }

      public void setEditable(boolean myEditable) {
            componentTextField.setEditable(myEditable);
            isEditable = myEditable;
      }

      public void setMonthScrollRate(int myMonthScrollRate) {
            monthScrollRate = myMonthScrollRate;
      }

      public void setPopupFont(Font myFont) {
            monthButton.setFont(myFont);
            todayButton.setFont(myFont);
            noneButton.setFont(myFont);
            Component[] dayHeaderLabels = dayHeaderPanel.getComponents();
            for (int i=0; i < dayHeaderLabels.length; i++) {
                  dayHeaderLabels[i].setFont(myFont);
            }
            Component[] dayLabels = dayPanel.getComponents();
            for (int i=0; i < dayLabels.length; i++) {
                  dayLabels[i].setFont(myFont);
            }
      }

      public void setTextFont(Font myFont) {
            componentTextField.setFont(myFont);
      }

///////////////////
// Listeners
///////////////////

      public void actionPerformed(ActionEvent evt) {
            Object source = evt.getSource();
            if (source == componentButton) {
                  Point myOrigin = componentButton.getLocationOnScreen();
                  Dimension buttonSize = componentButton.getSize();
                  popupCalendar.pack();
                  Dimension mySize = popupCalendar.getSize();
                  myOrigin.translate((buttonSize.width - mySize.width), (buttonSize.height));
                  popupCalendar.setLocation(myOrigin);
                  popupCalendar.setVisible(true);
                  }
            if (source == todayButton) {
                  selectedDate = todaysCalendar.getTime();
                  selectedCalendar.setTime(selectedDate);
                  selectedYear = selectedCalendar.get(Calendar.YEAR);
                  selectedMonth = selectedCalendar.get(Calendar.MONTH);
                  selectedDay = selectedCalendar.get(Calendar.DAY_OF_MONTH);
                  componentTextField.setText(returnDateFormatter.format(selectedDate));
                  popupCalendar.setVisible(false);
                  displayedCalendar.setTime(selectedDate);
                  updateCalendarDisplay();
            }
            if (source == noneButton) {
                  componentTextField.setText(null);
                  popupCalendar.setVisible(false);
                  selectedYear = 0;
                  selectedMonth = 0;
                  selectedDay = 0;
                  updateCalendarDisplay();

            }
      }

      public void mousePressed(MouseEvent evt) {
            Object source = evt.getSource();
            if (dayMap.containsKey(source)) {
                  selectedDate = (Date)dayMap.get(source);
                  selectedCalendar.setTime(selectedDate);
                  selectedYear = selectedCalendar.get(Calendar.YEAR);
                  selectedMonth = selectedCalendar.get(Calendar.MONTH);
                  selectedDay = selectedCalendar.get(Calendar.DAY_OF_MONTH);
                  componentTextField.setText(returnDateFormatter.format(selectedDate));
                  popupCalendar.setVisible(false);
                  updateCalendarDisplay();
            } else if (source == prevButton) {
                  displayedCalendar.roll(Calendar.MONTH, -1);
                  if (displayedCalendar.get(Calendar.MONTH)==Calendar.DECEMBER) {displayedCalendar.roll(Calendar.YEAR, -1);}
                  updateCalendarDisplay();
                  prevMonthTimer.start();
            } else if (source == nextButton) {
                  displayedCalendar.roll(Calendar.MONTH, 1);
                  if (displayedCalendar.get(Calendar.MONTH)==Calendar.JANUARY) {displayedCalendar.roll(Calendar.YEAR, 1);}
                  updateCalendarDisplay();
                  nextMonthTimer.start();
            } else {
//                  Empty
            }
      }

      public void mouseReleased(MouseEvent evt) {
            Object source = evt.getSource();
            if (source == prevButton) {
                  prevMonthTimer.stop();
            } else if (source == nextButton) {
                  nextMonthTimer.stop();
            } else {
//                  Empty
            }
      }

      public void mouseEntered(MouseEvent evt) {
            Object source = evt.getSource();
//                  Empty
      }

      public void mouseExited(MouseEvent evt) {
            Object source = evt.getSource();
            if (source == prevButton) {
                  prevMonthTimer.stop();
            } else if (source == nextButton) {
                  nextMonthTimer.stop();
            } else {
//                  Empty
            }
      }

      public void mouseClicked(MouseEvent evt) {
//            Empty
      }

      ActionListener monthScrollListener = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                  Object source = evt.getSource();
                  if (source == prevMonthTimer) {
                        displayedCalendar.roll(Calendar.MONTH, -1);
                        if (displayedCalendar.get(Calendar.MONTH)==Calendar.DECEMBER) {displayedCalendar.roll(Calendar.YEAR, -1);}
                        updateCalendarDisplay();
                  } else if (source == nextMonthTimer) {
                        displayedCalendar.roll(Calendar.MONTH, 1);
                        if (displayedCalendar.get(Calendar.MONTH)==Calendar.JANUARY) {displayedCalendar.roll(Calendar.YEAR, 1);}
                        updateCalendarDisplay();
                  } else {
//                        Empty
                  }
            }
      };

///////////////////
// Private Methods
///////////////////

      private void layoutControl() {
            //The visible controls
            BorderLayout componentLayout = new BorderLayout(componentMargin,0);
            setLayout(componentLayout);
            componentTextField = new JTextField(12);
            add(componentTextField, BorderLayout.CENTER);
                ImageIcon downArrow = new ImageIcon("M:\\MGC_Reports\\Images\\Downarrow.gif");
            componentButton = new JButton(downArrow);
            componentButton.addActionListener(this);
            componentButton.setFocusPainted(false);    
            add(componentButton, BorderLayout.EAST);
            setBorder(BorderFactory.createEmptyBorder(componentMargin,componentMargin,componentMargin,componentMargin));
            addMouseListener(this);
      }

      private void layoutCalendarWindow() {
            todaysDate = new Date();
            todaysCalendar = new GregorianCalendar();
            todaysCalendar.setTime(todaysDate);
            todaysYear = todaysCalendar.get(Calendar.YEAR);
            todaysMonth = todaysCalendar.get(Calendar.MONTH);
            todaysDay = todaysCalendar.get(Calendar.DAY_OF_MONTH);

            selectedDate = null;
            selectedCalendar = new GregorianCalendar();
            selectedYear = 0;
            selectedMonth = 0;
            selectedDay = 0;

            displayedDate = new Date();
            displayedCalendar = new GregorianCalendar();
            displayedCalendar.setTime(displayedDate);

            popupCalendar = new JDialog((Frame)this.getTopLevelAncestor(), true);
            popupCalendar.setUndecorated(true);

            JPanel monthPanel = new JPanel(new BorderLayout());
            monthPanel.setBorder(BorderFactory.createEtchedBorder());
                  ImageIcon leftButtonIcon = new ImageIcon("M:\\MGC_Reports\\Images\\Leftarrow.gif");
                  prevButton = new JButton(leftButtonIcon);
                  prevButton.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
                  prevButton.setPressedIcon(prevButton.getIcon()) ;
                  prevButton.setFocusPainted(false);
                  prevButton.addMouseListener(this);
                  prevMonthTimer = new javax.swing.Timer((1000/monthScrollRate), monthScrollListener);
                  prevMonthTimer.setInitialDelay(1000);
                  monthPanel.add(prevButton, BorderLayout.WEST);

                  monthButton = new JLabel("SEPTEMBER 8888", JLabel.CENTER);
                  monthButton.setBorder(null);
                  monthButton.addMouseListener(this);
                  monthPanel.add(monthButton, BorderLayout.CENTER);

                  ImageIcon rightButtonIcon = new ImageIcon("M:\\MGC_Reports\\Images\\Rightarrow.gif");
                  nextButton = new JButton(rightButtonIcon);
                  nextButton.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
                  nextButton.setPressedIcon(nextButton.getIcon()) ;
                  nextButton.setFocusPainted(false);
                  nextButton.addMouseListener(this);
                  nextMonthTimer = new javax.swing.Timer((1000/monthScrollRate), monthScrollListener);
                  nextMonthTimer.setInitialDelay(1000);
                  monthPanel.add(nextButton, BorderLayout.EAST);

            dayHeaderPanel = new JPanel(new GridLayout(1, 7, 2, 2));
            dayHeaderPanel.setBackground(Color.white);
                  JLabel dayTitleLabel1 = new JLabel("S", JLabel.RIGHT);
                  dayTitleLabel1.setBackground(Color.white);
                  dayTitleLabel1.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel1);
                  JLabel dayTitleLabel2 = new JLabel("M", JLabel.RIGHT);
                  dayTitleLabel2.setBackground(Color.white);
                  dayTitleLabel2.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel2);
                  JLabel dayTitleLabel3 = new JLabel("T", JLabel.RIGHT);
                  dayTitleLabel3.setBackground(Color.white);
                  dayTitleLabel3.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel3);
                  JLabel dayTitleLabel4 = new JLabel("W", JLabel.RIGHT);
                  dayTitleLabel4.setBackground(Color.white);
                  dayTitleLabel4.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel4);
                  JLabel dayTitleLabel5 = new JLabel("T", JLabel.RIGHT);
                  dayTitleLabel5.setBackground(Color.white);
                  dayTitleLabel5.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel5);
                  JLabel dayTitleLabel6 = new JLabel("F", JLabel.RIGHT);
                  dayTitleLabel6.setBackground(Color.white);
                  dayTitleLabel6.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel6);
                  JLabel dayTitleLabel7 = new JLabel("S", JLabel.RIGHT);
                  dayTitleLabel7.setBackground(Color.white);
                  dayTitleLabel7.setForeground(Color.black);
                  dayHeaderPanel.add(dayTitleLabel7);

            dayPanel = new JPanel(new GridLayout(6, 7, 2, 2));
            dayPanel.setBackground(Color.white);
            dayPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.black));

                  for (int i=0; i < dayLabel.length; i++) {
                        dayLabel[i] = new JLabel("0", JLabel.RIGHT);
                        dayLabel[i].setOpaque(true);
                        dayLabel[i].setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
                        dayLabel[i].addMouseListener(this);
                        dayPanel.add(dayLabel[i]);
                  }

            updateCalendarDisplay();

            JPanel buttonPanel = new JPanel(new GridLayout(1,2,6,6));
            buttonPanel.setBackground(Color.white);
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
                  todayButton = new JButton("Today");
                  todayButton.setMargin(new Insets(2, 2, 2, 2));
                  todayButton.setFocusPainted(false);
                  todayButton.addActionListener(this);
                  buttonPanel.add(todayButton);

                  noneButton = new JButton("None");
                  noneButton.setMargin(new Insets(2, 2, 2, 2));
                  noneButton.setFocusPainted(false);
                  noneButton.addActionListener(this);
                  buttonPanel.add(noneButton);


            GridBagLayout bottomPanelGridBag = new GridBagLayout();
            JPanel bottomPanel = new JPanel(bottomPanelGridBag);
            bottomPanel.setBackground(Color.white);
            bottomPanel.setBorder(BorderFactory.createEmptyBorder(0,15,0,15));
            GridBagConstraints bottomPanelConstraints = new GridBagConstraints();
                  buildConstraints(bottomPanelConstraints, 0, 0, 1, 1, 1, 0);
                  bottomPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
                  bottomPanelConstraints.anchor = GridBagConstraints.CENTER;
                  bottomPanelGridBag.setConstraints(dayHeaderPanel, bottomPanelConstraints);
                  bottomPanel.add(dayHeaderPanel);

                  buildConstraints(bottomPanelConstraints, 0, 1, 1, 1, 1, 0);
                  bottomPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
                  bottomPanelConstraints.anchor = GridBagConstraints.CENTER;
                  bottomPanelGridBag.setConstraints(dayPanel, bottomPanelConstraints);
                  bottomPanel.add(dayPanel);

                  buildConstraints(bottomPanelConstraints, 0, 2, 1, 1, 0, 0);
                  bottomPanelConstraints.fill = GridBagConstraints.BOTH;
                  bottomPanelGridBag.setConstraints(buttonPanel, bottomPanelConstraints);
                  bottomPanel.add(buttonPanel);

            GridBagLayout mainPanelGridBag = new GridBagLayout();
            JPanel mainPanel = new JPanel(mainPanelGridBag);
//            mainPanel.setBorder(BorderFactory.createRaisedBevelBorder());
            mainPanel.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.black));
            GridBagConstraints mainPanelConstraints = new GridBagConstraints();
                  buildConstraints(mainPanelConstraints, 0, 0, 1, 1, 0, 0);
                  mainPanelConstraints.fill = GridBagConstraints.BOTH;
                  mainPanelGridBag.setConstraints(monthPanel, mainPanelConstraints);
                  mainPanel.add(monthPanel);

                  buildConstraints(mainPanelConstraints, 0, 1, 1, 1, 1, 0);
                  mainPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
                  mainPanelConstraints.anchor = GridBagConstraints.CENTER;
                  mainPanelGridBag.setConstraints(bottomPanel, mainPanelConstraints);
                  mainPanel.add(bottomPanel);

            Container contentPane = popupCalendar.getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);

            popupCalendar.pack();
      }

      private void updateCalendarDisplay() {
            monthButton.setText(monthyearFormatter.format(displayedCalendar.getTime()));

            displayedCalendar.set(Calendar.DAY_OF_MONTH, 1);
            int firstDayOfDisplayedMonth = displayedCalendar.get(Calendar.DAY_OF_WEEK);
            int daysInDisplayedMonth = displayedCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            displayedCalendar.roll(Calendar.MONTH, -1);
            int daysInPrevDisplayedMonth = displayedCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            displayedCalendar.set(Calendar.DAY_OF_MONTH, daysInPrevDisplayedMonth);

            dayMap.clear();

            if (firstDayOfDisplayedMonth > 1) {
                  for (int i=(firstDayOfDisplayedMonth-2); i > (-1); i--) {
                        dayMap.put(dayLabel[i],displayedCalendar.getTime());
                        int thisYear = displayedCalendar.get(Calendar.YEAR);
                        int thisMonth = displayedCalendar.get(Calendar.MONTH);
                        int thisDay = displayedCalendar.get(Calendar.DAY_OF_MONTH);
                        dayLabel[i].setText(String.valueOf(thisDay));
                        if (thisYear==selectedYear && thisMonth==selectedMonth && thisDay==selectedDay) {dayLabel[i].setBackground(Color.lightGray); dayLabel[i].setForeground(Color.white);}
                        else {dayLabel[i].setBackground(Color.white); dayLabel[i].setForeground(Color.lightGray);}
                        if (thisYear==todaysYear && thisMonth==todaysMonth && thisDay==todaysDay) {dayLabel[i].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));}
                        else {dayLabel[i].setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));}
                        displayedCalendar.roll(Calendar.DAY_OF_MONTH, -1);
                  }
            }

            displayedCalendar.roll(Calendar.MONTH, 1);
            displayedCalendar.set(Calendar.DAY_OF_MONTH, 1);

            for (int i=(firstDayOfDisplayedMonth-1); i < (firstDayOfDisplayedMonth+daysInDisplayedMonth-1); i++) {
                  dayMap.put(dayLabel[i],displayedCalendar.getTime());
                  int thisYear = displayedCalendar.get(Calendar.YEAR);
                  int thisMonth = displayedCalendar.get(Calendar.MONTH);
                  int thisDay = displayedCalendar.get(Calendar.DAY_OF_MONTH);
                  dayLabel[i].setText(String.valueOf(thisDay));
                  dayLabel[i].setForeground(Color.black);
                  if (thisYear==selectedYear && thisMonth==selectedMonth && thisDay==selectedDay) {dayLabel[i].setBackground(Color.lightGray); dayLabel[i].setForeground(Color.white);}
                  else {dayLabel[i].setBackground(Color.white); dayLabel[i].setForeground(Color.black);}
                  if (thisYear==todaysYear && thisMonth==todaysMonth && thisDay==todaysDay) {dayLabel[i].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));}
                  else {dayLabel[i].setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));}
                  displayedCalendar.roll(Calendar.DAY_OF_MONTH, 1);
            }

            displayedCalendar.roll(Calendar.MONTH, 1);
            displayedCalendar.set(Calendar.DAY_OF_MONTH, 1);

            for (int i=(firstDayOfDisplayedMonth+daysInDisplayedMonth-1); i < dayLabel.length; i++) {
                  dayMap.put(dayLabel[i],displayedCalendar.getTime());
                  int thisYear = displayedCalendar.get(Calendar.YEAR);
                  int thisMonth = displayedCalendar.get(Calendar.MONTH);
                  int thisDay = displayedCalendar.get(Calendar.DAY_OF_MONTH);
                  dayLabel[i].setText(String.valueOf(thisDay));
                  dayLabel[i].setForeground(Color.lightGray);
                  if (thisYear==selectedYear && thisMonth==selectedMonth && thisDay==selectedDay) {dayLabel[i].setBackground(Color.lightGray); dayLabel[i].setForeground(Color.white);}
                  else {dayLabel[i].setBackground(Color.white); dayLabel[i].setForeground(Color.lightGray);}
                  if (thisYear==todaysYear && thisMonth==todaysMonth && thisDay==todaysDay) {dayLabel[i].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));}
                  else {dayLabel[i].setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));}
                  displayedCalendar.roll(Calendar.DAY_OF_MONTH, 1);
            }
            displayedCalendar.roll(Calendar.MONTH, -1);
            displayedCalendar.set(Calendar.DAY_OF_MONTH, 1);
      }

      private void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
            gbc.gridx = gx;
            gbc.gridy = gy;
            gbc.gridwidth = gw;
            gbc.gridheight = gh;
            gbc.weightx = wx;
            gbc.weighty = wy;
      }



//                  JOptionPane.showMessageDialog(null, "The calender will pop up!", "Debug", JOptionPane.INFORMATION_MESSAGE);
}



Thanks for any help you can give!
0
Comment
Question by:mgcIT
  • 4
  • 4
  • 3
11 Comments
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
Call the setSize () or setPreferredSize () method on the components for setting the size.
0
 
LVL 18

Author Comment

by:mgcIT
Comment Utility
>> Call the setSize () or setPreferredSize () method on the components for setting the size.

but if I call objDC.setSize() won't that change the size of both pieces (the textbox and button)?  How do I change the size of each piece individually?
0
 
LVL 10

Expert Comment

by:ADSLMark
Comment Utility
You can adjust the method layoutControl() in any way to display th controls like you want. The programmer of the DateChooser made a small mistake by not allowing you to override this method, so you have to hack your way in. You could also make the method public and then override it with your own custom extended DateChooser (which is just more work for the same thing).
So basically just change the code in layoutControl(), for example:

      private void layoutControl()
      {
            setLayout(new FlowLayout());

            componentTextField = new JTextField(12);
            add(componentTextField);

            componentButton = new JButton("Choose date");
            componentButton.addActionListener(this);
            add(componentButton);

            addMouseListener(this);
      }

with the following code:

import java.awt.*;
import javax.swing.*;

public class DateExample
    extends JFrame
{
    public DateExample()
    {
        setSize(600,400);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateChooser objDC = new DateChooser();
        getContentPane().add(objDC);
        objDC.setEditable(false);
    }

    public static void main(String[] args)
    {
        new DateExample().setVisible(true);
    }
}

Good luck,
Mark
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> How do I change the size of each piece individually?

textBox.setSize ( width, height ) ;
button.setSize ( width, height ) ;
0
 
LVL 18

Author Comment

by:mgcIT
Comment Utility
Thanks for the replies.

mayankeagle:

even after setting the components to public (they were set as private) setting the size does nothing.  I cannot change the height or width using:

objDC.componentTextField.setSize(20, 20);

ADSLMark:
You kind of lost me here... I see you want me to modify the LayoutControl() method, but then what is the other class you have there?  If that is just an example on how to implement it, I still don't see how I can set the size of the 2 components individually.  you have:

setSize(600, 400) >> what is this setting the size of? Not the DateChooser right?

Thanks again for the help!
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 10

Expert Comment

by:ADSLMark
Comment Utility
You can just adjust the layoutcontrol() method and set size there. For example:

private void layoutControl()
      {
            setLayout(new FlowLayout());

            componentTextField = new JTextField(12);
            add(componentTextField);

            componentButton = new JButton("Choose date");
            componentButton.addActionListener(this);
            add(componentButton);

            addMouseListener(this);
      }

Here i changed the whole layoutControl() method to be shown as a FlowLayout. One button with "Choose Date" and another textfield. The other code i showed just displays this.
So by changing the layoutCOntrol you could also specify a null-layout to use setBounds() for example.
This is kinda a *hack* to get things *right*. If you want a more clean solution you can also add methods to the DateChooser class and modify the controls directly. You still have to change the layoutControl() to "break" the layout *as it is now*.

In some other words, the DateChooser is a component which has a layout. This layout is currently *fixed*, so you cannot change the size of the individual components. A way to change the size of the individual components is to change the layout *inside* the DateChooser component. The layout is now set in the layoutControl() method, so if you *change* that method, you can set your *own* layout for the individual components of the DateChooser component.

In again other words, see the DateChooser as a box with two boxes inside. You define the outer-box with datechooser.setSize(..), and the layoutcontrol() (in DateChooser) will determine how big the boxes inside will be. If you want to set the size of the boxes inside *yourself* then you have to make them accessible outside the DateChooser (by making separate methods inside the DateChooser which modify the dimensions) or redefine the layoutControl() method in DateChooser to make the boxes inside have different dimensions. If you want them accessible from outside the DateChooser then you also need to redefine the layoutControl() method, because it uses a fixed layout now, which cannot be modified by having methods which change the controls directly.

I hope it's clear now.
Mark
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> setting the size does nothing

Try with setPreferredSize () too
0
 
LVL 18

Author Comment

by:mgcIT
Comment Utility
ok a couple things here...

I think a null layout would be preferred so I can just set the size & bounds for each component individually.

can you help me with those methods?

I am having problems with your DateExample class (the JFrame never appears) but I'm not really concerned with that.  As long as you can show me how to use the null layout and create/initialize my DateChooser objects so I can put them wherever and have them be any size.  

Lastly, my JButton will use an ImageIcon instead of a string label like so:

ImageIcon downArrow = new ImageIcon("C:\\Images\\Downarrow.gif");
componentButton = new JButton(downArrow);

Not sure if that matters but just wanted to point that out.

Thanks!
0
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
Comment Utility
Change layoutControl() like, you can set whatever size you want...

      private void layoutControl()
      {
            setLayout(null);

            componentTextField = new JTextField(12);
            componentTextField.setBounds(getX(),getY(),100,20);
            add(componentTextField);

            ImageIcon downArrow = new ImageIcon("C:\\Images\\Downarrow.gif");
            componentButton = new JButton(downArrow);
            componentButton.setBounds(getX()+100,getY(),40,20);
            componentButton.addActionListener(this);
            add(componentButton);

            addMouseListener(this);
      }

Don't forget to set the bounds of the datechooser itself. It might be kind of struggle to get things *right* so, don't give up too soon. First set the x,y and w,h of the datechooser, then you can use getX() getY() etc. to set the individual positions/dimensions.
Code copied from your first post:

        DateChooser objDC = new DateChooser();
        objDC.setEditable(false);
        objDC.setBounds(30, 110, 140, 20);
        getContentPane().add(objDC);

Mark
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> I think a null layout would be preferred so I can just set the size & bounds for each component individually

Ah yes I was waiting for this!

If you'd like a null layout, you have full control over the component's size.
0
 
LVL 18

Author Comment

by:mgcIT
Comment Utility
sorry for such a long delay on this - I had some other problems that required my attention.

After finally getting to test this I was able to get it working.  Thanks very much for the help!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now