日期格式化文本框

日期格式化文本框

本文介绍了日期格式化文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让文本框使用格式 dd / mm / yyyy 进行验证,不允许任何其他字符?我已经设法验证它,所以它只是数字,但数字和斜杠被证明是一个问题。

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.

我正在使用 JAVAFX

推荐答案

我已经创建了一个基于文本框的日期控件:
它允许您设置格式(由...支持SimpleDateFormat),并支持鼠标选择弹出窗口。

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).

一些示例代码(也可以在github的测试类中找到):

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
    }
});

更新

添加过滤器逻辑。如果您设置过滤器,则可以限制用户输入的可接受日期。不可接受的日期将在GUI中显示为灰色,用户也将被禁止在文本字段中手动输入。

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;
            }
        }
    });

这篇关于日期格式化文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:45