2014-02-24 124 views
0

我想製作一個應該像使用adressbook一樣使用的JTable。 所以有一個按鈕是用來創建新的entrys。 我想通過使用JOptionPane InpuDialog來創建這些entrys,因爲我希望只創建至少包含名稱和年齡的 Entrys。 另外我想檢查有沒有重複(相同的名稱)。 所以我發佈你我的添加按鈕的代碼。 檢查年齡介於1到100之間是否正確,但我忘記檢查所選名稱是否確實不是重複的,如果您點擊確定按鈕,他會接受重複項。 所以我的問題是,如果它適用於實現與我同時循環檢查(像我下波紋管)或有更容易的方法來實現它?檢查JOptionPane輸入是否正確

     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 
            } 
+0

當然,你可以做一個while循環。當你嘗試時發生了什麼? –

+0

工作正確,但我認爲可能會有更好的解決方案 – Jaran

回答

0

我的建議是創建一個名爲名爲控制器的驗證文件包驗證文件創建一個類驗證絲毫兩種方法之一進行檢查的名稱和其他用於檢查的年齡範圍,然後調用該方法,這是爲了重新使用你的代碼並且簡化了。

相關問題