我想捕獲所有異常到一個parseInt請求與相同的響應,所以如果字符串不解析爲一個int,它執行catch下的代碼。這會產生一個簡單的驗證循環,要求他們每次嘗試離開該字段時都要再次嘗試,而不必輸入有效的int。現在它會在系統控制檯中拋出異常,但不會返回我的預配置錯誤消息並運行相關的代碼。java parseInt異常沒有被捕獲
public static void main(String[] args){
//draw and show the GUI
JFrame GUI = new JFrame();
GUI.setTitle("New Provider Interface");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textID = new JTextField("providerID ", 20);
final JTextField textName = new JTextField("Provider Name ", 20);
FocusGrabber fgID = new FocusGrabber(textID);
GUI.add(textID);
GUI.add(textName);
GUI.pack();
GUI.setVisible(true);
}
textID.addFocusListener(new FocusListener(){ @Override
public void focusGained(FocusEvent e) {/* */}
@Override public void focusLost(FocusEvent e) {
if (!e.isTemporary()) {
String checkID = textID.getText();
Boolean validID = false;
if (checkID.isEmpty()){JOptionPane.showMessageDialog(mainFrame, "Please enter a valid ID."); fgID.run();}
else while (validID = false){try {
String sID = textID.getText();
int iID = Integer.parseInt(sID);
}catch (Exception e1){
JOptionPane.showMessageDialog(mainFrame, checkID + "is not a valid ID. Please try again.");
fgID.run();
}finally {validID= true;}
} } } } );
使用JSpinner的,JFormattedTextField上和/或InputVerifier使你更容易 – MadProgrammer
一個InputVerifier可以用來不僅VERI fy你的領域的內容,但限制從失去焦點audiblematically – MadProgrammer
你的while循環是非常危險的,可能導致你的程序掛起 – MadProgrammer