对于多JTextField的空字符串验证 [英] Empty String validation for Multiple JTextfield
问题描述
有没有一种方法来验证数字在java中JTextField的的没有别的,如果结构。我有一组13字段,我想要的错误消息时没有条目给出为任何的13场,并能够将焦点设置到该特定的文本框。这是prevent用户进入空数据到数据库中。可能有人告诉我如何可以不喜欢下面的if else结构来实现。
Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.
if (firstName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else {
//code to enter values into MySql database
以上code来actionPerformed方法一个一个提交按钮注册下。尽管为NOT NULL在MySQL中设置领域,空字符串正在从Java GUI接受。为什么是这样?我希望也许是一个空字符串异常可能会被抛出从中我可以自定义验证消息,但无法做到为空字段正在接受。
the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.
感谢
推荐答案
有多种方法可以做到这一点,一个是
There are multiple ways to do this, one is
JTextField[] txtFieldA = new JTextField[13] ;
txtFieldFirstName.setName("First Name") ; //add name for all text fields
txtFieldA[0] = txtFieldFirstName ;
txtFieldA[1] = txtFieldLastName ;
....
// in action event
for(JTextField txtField : txtFieldA) {
if(txtField.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
//break it to avoid multiple popups
break;
}
}
另外,请看看 JGoodies数据验证该框架可帮助您验证用户输入在Swing应用程序,并帮助您验证报告错误和警告。
Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.
这篇关于对于多JTextField的空字符串验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!