Java JTextfields [duplicate]
Just a quick question, How do i ensure my JtextField only accepts numeric values? I want it to to diplsy an error message if the user entered anything else thank you
You can use a JFormattedTextField
. Construct it using a NumberFormatter
and it will only accept numbers.
The JFormattedTextField
has a bunch of configurable options that let you decide how bad input is handled. I recommend looking at the documentation.
You can either add a key event listener and check each char typed in or there are document formatters (NumberFormatter) you can install that will not allow you to enter anything but a number.
Associate a key listener with the text field and check for the value just inserted. If value inserted is not an integer, then prompt error.
I use this trick.
private void myTextFieldKeyReleased(java.awt.event.KeyEvent evt) {
try{
int i = Integer.parseInt(myTextField.getText());
}
catch(Exception ex){
//Show error message here with
JOptionPane.showMessageDialog(null, "Invalid Input...!");
myTexTField.setText("");
}
}
精彩评论