JTextField的用户输入实时格式 [英] JTextField's real time formatting of user input

查看:116
本文介绍了JTextField的用户输入实时格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在输入时实时格式化用户输入.

I would like to format the user input in real time, while they are typing.

例如,如果希望用户输入日期,则希望文本字段以浅灰色显示日期格式.用户只能在输入时输入有效数字.

For example, if I want the user to enter a date, I would like the text field to show in light gray the date format. The user would only be able to enter valid digits while he is typing.

如果我需要用户输入电话号码,则该格式将在文本字段中以浅灰色显示,并且用户只能输入有效数字...

If I need the user to enter a phone number, the format would be displayed in light gray in the text field and the user would only be able to enter valid digits...

有关此示例的javascript示例: http://omarshammas.github.io/formancejs#dd_mm_yyyy

A javascript example of this can be found here: http://omarshammas.github.io/formancejs#dd_mm_yyyy

我看了看JFormattedTextField,但它似乎并不能阻止用户键入错误的字符.

I looked at JFormattedTextField but it seems it doesn't prevent the user from typing wrong characters.

我想知道如何在Java中执行与上面链接的javascript代码相同的操作.

I am wondering how to do the same thing in Java as the javascript code linked above.

有什么想法可以帮助我入门,或者任何lib已在执行此操作?

Any idea to help me get started or any lib already doing this?

预先感谢您的任何建议.

Thanks in advance for any suggestion.

推荐答案

KeyListener 接口具有三种要实现的方法:keyPressed,keyTyped和keyReleased.按下每个键时,您可以在此实现的侦听器中执行所需的操作.因此,例如,如果当前键入的键或文本字段的当前内容未得到您的认可,则可以采取视觉或逻辑操作.

The KeyListener interface has three methods to be implemented: keyPressed, keyTyped and keyReleased. As each key is pressed you can do what you need to in this implemented listener. So for example, if the current key typed or the current contents of the text field is not to your approval, you can take the visual or logical action you need to take.

我一般不喜欢链接,但是此处很小有关KeyListener的教程.

I don't like links generally, but here is a small tutorial on KeyListeners.

下面是将KeyListener添加到JTextField的示例:

And here is an example to add a KeyListener to a JTextField:

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }

    public void keyTyped(KeyEvent e) {
        // TODO: Do something for the keyTyped event
    }

    public void keyPressed(KeyEvent e) {
        // TODO: Do something for the keyPressed event
    }
});

这篇关于JTextField的用户输入实时格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆