ActionPerformed and ActionListener

My program asks the user: How many course have you completed? So, the users has to enter the number of courses completed on a JTextField component. My program then converts the String that has been entered in the JTextField into a Integer. When I run my program, I get a numberformatException. I tried debugging, and I noticed that my program converts the String into a Integer before the user can write anything. The program doesn't wait for the user to type anything. How can I make so my program waits for the user to enter a number before continuing to execute the code?

public class content extends JPanel implements ActionListener
{

     String number = "";
     JTextField NumtextField = new JTextField(5);

     @Override
     public void actionPerformed(ActionEvent e)
     {
         number = NumtextField.getNumtextField().getText();
     }

     int size = Integer.parseInt(number);

}

Answers


Move int size = Integer.parseInt(number); inside actionPerformed:

 public void actionPerformed(ActionEvent e){
 number = NumtextField.getNumtextField().getText();
 int size = Integer.parseInt(number);
 }

When the program starts, its trying to parse "", which is not a valid number string hence why you are getting an exception. Also maybe you should put that inside a try{}catch{} block, so in case you get an exception in real time you can handle it:

try {
 int size = Integer.parseInt(number);
}
catch (NumberFormatException e) {
System.out.println("Thats not a valid number");
}

Need Your Help

Eclipse marks lines as dead code

java eclipse dead-code

I have this function with some dead code, marked by Eclipse.

Handling Redirection in .NET WebRequest

c# webrequest

I'm behind a firewall that asks me to enter credentials before letting me access internet. So my first http request is intercepted and then redirected to a secure server that prompts me to enter my

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.