Question

I want to use 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());
}
Était-ce utile?

La solution

You have the try/catch in the wrong place. You need to put it inside the actionPerformed method.

 public void actionPerformed(ActionEvent e ) {
   try {
    int a = Integer.parseInt( t1.getText() );
   }
   catch(NumberFormatException e ) {
     System.out.println( e.getMessage() );
   }
 }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top