2014-05-04 141 views
0

我有一個圖形用戶界面設計,有許多字段,用戶輸入。我正在使用try-catch來處理用戶錯誤輸入的異常。當用戶在字段中輸入一個字符串時,我很成功(我的id字段),但我很沮喪,試圖在用戶在文本/字符串字段中輸入整數時使用異常來處理。 這裏是我的代碼,讓你知道我爲我成功的例外做了些什麼。謝謝。Java GUI Jframe異常處理

try { 

    String taskID = txtId.getText(); 
    int id = Integer.parseInt(taskID); 

    String taskName = txtName.getText(); 

    String taskDesc = txtDesc.getText(); 

    boolean isCompleted = chkComp.isSelected(); 

    int taskPriority = comboPriority.getSelectedIndex(); 

    Task newTask = new Task(id, taskName, taskDesc, isCompleted, taskPriority); 

    tasks.add(newTask); 
    taskMod.addElement(newTask); 

} catch (NumberFormatException e) { 
    JOptionPane.showMessageDialog(null, "Error: You must enter an integer"); 

} 
+0

你好,謝謝你的回覆,但什麼時候運異常會那是?像這是一個「NumberFormatException」?對不起,我是新來學習這個。 – user3597639

+0

嗯,我在這裏有點困惑。你的目標是讓程序再次提示嗎? – BitNinja

+0

是的,我的目標是提示用戶「你必須在名稱中輸入一個字符串而不是整數」..很抱歉,如果我沒有太大的意義。我的目標是讓它提示出現任何錯誤 – user3597639

回答

1

我有另一種選擇,你可以實時驗證輸入,DocumentFilter。有了這個,你可以驗證每個字符輸入。如果角色不符合您的要求,則不允許輸入。

這裏是數字只有

private JTextField createNumberField() { 
    JTextField field = new JTextField(20); 
    ((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() { 
     @Override 
     public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
       throws BadLocationException { 
      fb.insertString(off, str.replaceAll("\\D", ""), attr); // remove non-digits 
     } 

     @Override 
     public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
       throws BadLocationException { 
      fb.replace(off, len, str.replaceAll("\\D", ""), attr); // remove non-digits 
     } 
    }); 
    return field; 
} 

這裏是一個名稱(字母, - 和空格)被允許