Frage

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

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

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

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

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

Thanks in advance for any suggestion.

War es hilfreich?

Lösung

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.

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

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
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top