i want to make a JTable which should be used like a adressbook. so there is a button which is used to create new entrys. I want to create these entrys by using JOptionPane InpuDialog because I want that only Entrys with at least name and age are created. Also i want to Check that there are no duplicates (same name). So i post you the code of my add-button. The check if the age ist between 1 and 100 works correct but i forget to check if the selected name is really not a duplicate, if you click the ok-button wo times he accept duplicates. So my question is if it is applicable to realize the check with i while loop ( like i did down bellow) or is there an easier way to realize it?
boolean notAllowed=true;
boolean noCreation=false;
DefaultTableModel dtm = (DefaultTableModel) table
.getModel();
String s = JOptionPane.showInputDialog("Select Name");
for (int i = 0; i < dtm.getRowCount(); i++) {
if (s.equals(dtm.getValueAt(i, 0))) {
s = JOptionPane.showInputDialog("Selected Name already in use \n Select an other Name");
i = 0;
}
}
String c = JOptionPane
.showInputDialog("age?",JOptionPane.OK_OPTION);
while(notAllowed){
try{
int teste =Integer.parseInt(c);
if(teste==JOptionPane.CANCEL_OPTION)
{
notAllowed=false;
noCreation=true;
}
if(teste<=100 && teste>0 &¬Allowed)
notAllowed=false;
}
catch( Exception err)
{
notAllowed=false;
noCreation=true;
}
if(notAllowed)
c = JOptionPane.showInputDialog("Only Numbers between 1 and 100 are allowed");
}
if(!noCreation)
{
//create Entry
}
我的建议是在验证文件中的名为controller的包中创建一个名为Validation的文件在类Validation中创建两个方法,一种用于检查名称,另一种用于检查年龄范围,然后调用此方法,以供重新使用代码并简化。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.