Date Formatting Textbox

2019-07-23 14:17发布

问题:

Is there a way to have a textbox that validates with the format dd/mm/yyyy and doesn't allow any other characters? I've managed to validate it so it's only numbers but having numbers and slashes is proving to be an issue.

I am using JAVAFX.

回答1:

I have created a date control which is based on a textbox: https://github.com/nablex/jfx-control-date/ It allows you to set a format (supported by SimpleDateFormat) and supports a popup for mouse selection.

You can also enter values by typing (only valid values are allowed) and browse the fields with the arrow buttons (left & right will browse, up & down will increase/decrease).

Some example code (can also be found in the test class on github):

DatePicker picker = new DatePicker();

// you may not want the controls to manipulate time, they are on by default however
picker.setHideTimeControls(true);

// optional: the format you want the date to be in for the user
picker.formatProperty().setValue("yyyy/MM/dd HH:mm:ss.SSS");

// optional: set timezone
picker.timezoneProperty().setValue(TimeZone.getTimeZone("CET"));

// optional: set locale
picker.localeProperty().setValue(new Locale("nl"));

// react to changes
picker.timestampProperty().addListener(new ChangeListener<Long>() {
    @Override
    public void changed(ObservableValue<? extends Long> arg0, Long oldValue, Long newValue) {
        // do something
    }
});

UPDATE

Filter logic was added. If you set a filter, you can limit the dates that are acceptable for the user to enter. Unacceptable dates will be greyed out in the GUI and the user will also be prevented from entering them manually in the text field.

For example this filter will block any dates before a random point in time:

    picker.filterProperty().setValue(new DateFilter() {
        @Override
        public boolean accept(Date date) {
            SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
            try {
                return date.after(parser.parse("2010-07-13"));
            }
            catch (ParseException e) {
                return false;
            }
        }
    });