问题
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
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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("");
}
}
来源:https://stackoverflow.com/questions/4442004/java-jtextfields