5

I got the JDatePicker working, in my application, but want the date to be formatted as YYYY_MM_DD
Currently the date's format is the default Wed Jul 08 15:17:01 ADT 2015
From this guide there's a class that formats the date as follows.

package net.codejava.swing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JFormattedTextField.AbstractFormatter;

public class DateLabelFormatter extends AbstractFormatter {

    private String datePattern = "yyyy-MM-dd";
    private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

    @Override
    public Object stringToValue(String text) throws ParseException {
        return dateFormatter.parseObject(text);
    }

    @Override
    public String valueToString(Object value) throws ParseException {
        if (value != null) {
            Calendar cal = (Calendar) value;
            return dateFormatter.format(cal.getTime());
        }

        return "";
    }

}

So I added the class to my package and the Swing application has the proper constructor

JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());

So everytime I call datePicker.getModel().getValue().toString() the formatting is the original.
Now I see the DateLabelFormatter calls valueToString, but that method doesn't seem available in my application class.
Do I need to extend my application class?
Am I calling the wrong methods to get the information?
They're all in default package [not good?] is that causing problems ?

guy_sensei
  • 513
  • 1
  • 6
  • 21
  • 1
    Why are you calling `datePicker.getModel().getValue().toString()`? That's going to be calling `Date.toString()`. The point of providing a label formatter is for the date picker itself to use it in the text box... that's the *display* value... where are you trying to use that code, and why? – Jon Skeet Jul 07 '15 at 19:02
  • The method stringToValue() shoudl return a Calendar and not a Date, see my answer @ http://stackoverflow.com/questions/35264674/how-to-make-jdatepicker-text-field-formatted-for-input/41287665#41287665. – PJ_Finnegan Dec 22 '16 at 16:42

2 Answers2

7

http://www.codejava.net/java-se/swing/how-to-use-jdatepicker-to-display-calendar-component

Here might be a resource that can help

I believe you might need to call

datePicker.getJFormattedTextField().getText()
Huang Chen
  • 1,177
  • 9
  • 24
4

You have to call

datePicker.getJFormattedTextField().getText()

to get the displayed value from the datePicker

Madhan
  • 5,750
  • 4
  • 28
  • 61