سؤال

I want to catch NumberFormatException but my code have error, because I have TextField and a button in my program. If you enter the number in TextField, there is not any problem. If you enter a letter, I want to get error message but I don't use. please help me?

My code:

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());
}   
هل كانت مفيدة؟

المحلول

You're trying to catch the exception on the method that adds the action listener, not the method that actually tries to parse the string as an integer. If you wrap that in the try / catch block, then it should work as you expect:

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

Note that if this is a real world program you'll want to pop up a dialog (probably using JOptionPane) rather than print to the console, and you'll want to print something much more human readable then the exception error message.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top