Java JTextfields [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-11 08:05:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!