2013-12-21 81 views
1

我想使用NumberFormatException但我的代碼有錯誤,因爲我在我的程序中有TextField和一個按鈕。如果您在文本框中輸入數字,則沒有任何問題。 如果你輸入一個字母,我想得到錯誤信息,但是我不使用。請幫幫我?
我的代碼Java數字格式異常使用

private JTextField t1=new JTextField(10); 
private JButton o88 = new JButton("send"); 

try{ 
    o88.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      int a = 0; 
      a = Integer.parseInt(t1.getText()); 
     } 
    }); 
} 
catch (NumberFormatException e){ 
    System.out.println(e.getMessage()); 
} 
+0

它看起來像您的可執行代碼放在方法,構造函數或初始化程序之外。 – dasblinkenlight

回答

2

你在錯誤的地方try/catch語句。你需要把它放在actionPerformed方法中。

public void actionPerformed(ActionEvent e) { 
    try { 
    int a = Integer.parseInt(t1.getText()); 
    } 
    catch(NumberFormatException e) { 
    System.out.println(e.getMessage()); 
    } 
}