Java TextField日期自动填充

时间:2018-03-31 02:08:03

标签: java date codenameone java-date

好吧,我有这样的事情:

public void menu() {

        final Form menu = new Form("Menu");
        menu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        Button confirm = new Button("Confirm");

        Container creditCardContainer = new Container(new GridLayout(1, 3));

        final TextField num1 = new TextField(3);
        final TextField num2 = new TextField(3);
        final TextField num3 = new TextField(3);

        num1.setConstraint(TextArea.NUMERIC);
        num2.setConstraint(TextArea.NUMERIC);
        num3.setConstraint(TextArea.NUMERIC);

        creditCardContainer.addComponent(num1);
        creditCardContainer.addComponent(num2);
        creditCardContainer.addComponent(num3);

        Validator v = new Validator();

        v.addConstraint(num1, new LengthConstraint(2));
        v.addConstraint(num2, new LengthConstraint(2));
        v.addConstraint(num3, new LengthConstraint(4));

         automoveToNext(num1, num2);
         automoveToNext(num2, num3);

        menu.add(creditCardContainer);
        menu.add(confirm);
        v.addSubmitButtons(confirm);
        menu.show();

            confirm.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent ev) 
                {
                    String getdate = num1.getText() + "/" + num2.getText() + "/" + num3.getText();
                    System.out.println(getdate);
                    new StateMachine("/theme");
                }
            });
        }
    }

    private void automoveToNext(final TextField current, final TextField next) {
        current.addDataChangedListener(new DataChangedListener() {
            public void dataChanged(int type, int index) {
                if(current.getText().length() == 3) {
                    Display.getInstance().stopEditing(current);
                    String val = current.getText();
                    current.setText(val.substring(0, 2));
                    next.setText(val.substring(2));
                    Display.getInstance().editString(next, 3, current.getConstraint(), next.getText());
                }
            }
        });
    }

请注意,addDataChangeListener已弃用,因此我必须将其更改为addDataChangedListener

我认为我的代码有问题,因为当我在Codename One Simulator中运行它时,它仍允许我输入字母,即使使用下面的代码:

num1.setConstraint(TextArea.NUMERIC);
num2.setConstraint(TextArea.NUMERIC);
num3.setConstraint(TextArea.NUMERIC);

此外,当我完成输入日期后,我的确认按钮也不会突出显示。请有人帮我解决。

Obs:我的约会时间是dd / MM / yyyy

2 个答案:

答案 0 :(得分:2)

使用

try {
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Date date = format.parse("");
}catch (ParseException e) {
    System.out.println("Wrong format.");
}

检查日期是否为有效格式。

答案 1 :(得分:2)

我们不支持直接字段屏蔽,因为本机文本字段输入不能很好地处理。你有两个我能想到的选择:

  • 使用日期选择器启动一个出色的设备本机UI来选择日期。请注意,它在模拟器中不是很好,但在Android / iOS上看起来不错。

  • 使用3个文本字段,并在输入时自动移至下一个字段,就像我们对此信用卡输入样本所做的那样:http://www.codenameone.com/blog/validation-regex-masking.html

相关问题