How to make JDatePicker text field formatted for input?

∥☆過路亽.° 提交于 2020-01-04 09:38:28

问题


org.jdatepicker is used

In my app input field should be editable, so I added

    datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
    datePicker.setTextEditable(true);

But now I can write any bs to it: screenshot. I need to add something like

    mf = new MaskFormatter("##.##.####"); 
    mf .setPlaceholderCharacter('.');

to limit input to mask. But how to do this? JDatePickerImpl isn't a JFormattedTextField. When I choose date from calendar it's formatted right way. My DateLabelFormatter class:

    public class DateLabelFormatter extends JFormattedTextField.AbstractFormatter {
        private String datePattern = "dd.MM.yyyy";
        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 "";
        }
    }

added: Tried to extract JFormattedTextField from JDatePickerImpl and changed this way:

     datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
     datePicker.setTextEditable(true);

     MaskFormatter mf = new MaskFormatter("##.##.####");
     mf.setValidCharacters("1234567890");
     mf.setPlaceholderCharacter(' ');
     JFormattedTextField textField = datePicker.getJFormattedTextField();
     textField.setFormatterFactory(new DefaultFormatterFactory(mf));

It looks like I wanted now, but seems everything else went wrong and it's not returning date now.

also tried to change DateLabelFormatter class:

    public class DateLabelFormatter extends MaskFormatter {

private String datePattern = "dd.MM.yyyy";
private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
public DateLabelFormatter() { // set mask and placeholder
    try {
        setMask("##.##.####");

        setPlaceholderCharacter('0');
        setAllowsInvalid(false);
        setOverwriteMode(true);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
@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 dateFormatter.format(Calendar.DATE);
}

}

Everything looks fine now and even partially works - when I pick date from calendar. But when I type date from keyboard I get error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date cannot be cast to java.util.Calendar
at org.jdatepicker.impl.JDatePickerImpl$InternalEventHandler.propertyChange(JDatePickerImpl.java:247)
at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:328)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
at java.awt.Component.firePropertyChange(Component.java:8430)
at javax.swing.JFormattedTextField.setValue(JFormattedTextField.java:798)
at javax.swing.JFormattedTextField.commitEdit(JFormattedTextField.java:529)
at javax.swing.JFormattedTextField$FocusLostHandler.run(JFormattedTextField.java:648)
at javax.swing.JFormattedTextField.processFocusEvent(JFormattedTextField.java:630)
at java.awt.Component.processEvent(Component.java:6291)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:995)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:661)
at java.awt.Component.dispatchEventImpl(Component.java:4762)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

回答1:


I had the same problem: it seems that stringToValue() has to return an instance of Calendar and not of Date, symmetrically to valueToString() which receives a Calendar as an input. So the correct code would be:

public class DateLabelFormatter extends JFormattedTextField.AbstractFormatter {
    private String datePattern = "dd.MM.yyyy";
    private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

    @Override
    public Object stringToValue(String text) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime((Date) dateFormatter.parseObject(text));
        return cal;
    }

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


来源:https://stackoverflow.com/questions/35264674/how-to-make-jdatepicker-text-field-formatted-for-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!