问题
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.
回答1:
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
}
});
来源:https://stackoverflow.com/questions/23134329/jtextfields-real-time-formatting-of-user-input