繁体   English   中英

检查JOptionPane输入是否正确

[英]Check if JOptionPane input is correct

我想制作一个JTable,应该像地址簿一样使用。 因此,有一个用于创建新条目的按钮。 我想使用JOptionPane InpuDialog创建这些条目,因为我只希望创建至少具有名称和年龄的条目。 我也想检查是否没有重复(同名)。 因此,我向您发布了我的添加按钮的代码。 检查年龄ist是否在1到100之间是正确的,但是如果您单击确定按钮,他是否接受重复,则我忘记检查所选名称是否确实不是重复名称。 所以我的问题是,是否适用于使用i while循环来实现检查(就像我在波纹管下面那样)还是有一种更简单的方法来实现它?

                      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 &&notAllowed)
                        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中创建两个方法,一种用于检查名称,另一种用于检查年龄范围,然后调用此方法,以供重新使用代码并简化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM