views:

267

answers:

2

I have created the following class that extends JSpinner to iterate over dd/mm/yyy values.


public class DateSpinner extends JSpinner{

    Calendar calendar = new GregorianCalendar();

    public DateSpinner(){
    super();

    calendar.add(Calendar.DAY_OF_YEAR, 1);
    Date now = calendar.getTime();

    calendar.add(Calendar.DAY_OF_YEAR, -2);
    Date startDate = calendar.getTime();

    calendar.add(Calendar.YEAR, 100);
    Date endDate = calendar.getTime();

    SpinnerDateModel dateModel = new SpinnerDateModel
        ( now , startDate , endDate , Calendar.DAY_OF_MONTH );

    setModel(dateModel);

    JFormattedTextField tf =
        ((JSpinner.DefaultEditor)getEditor()).getTextField();
    DefaultFormatterFactory factory =
        (DefaultFormatterFactory)tf.getFormatterFactory();
    DateFormatter formatter = (DateFormatter)factory.getDefaultFormatter();

    // Change the date format to only show the hours
    formatter.setFormat(new SimpleDateFormat("dd/MM/yyyy"));
    }




}

My problem is when i set its value using

    Date today = new Date();
    spinner.setValue(today);

I get the date including the time and day of the week. if i touch the spinner it formats it according to the format i set. How can i initially get the format i want to be shown.

+2  A: 

Use built-in editors, such as following

spinner.setEditor(new JSpinner.DateEditor(spinner, "dd/MM/yyyy"));
eugener
A: 

Also, as a side note - whenever you work with calendars, dates and times I would consider using Joda Time.

javamonkey79