开发者

Java JTextfields [duplicate]

This question already has answers here: 开发者_StackOverflow Is there any way to accept only numeric values in a JTextField? (20 answers) Closed 7 years ago.

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("");
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜