• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing data with a btnClick to another class which implements ActionListener

 
Chris Green
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I created 3 java classes (.java files)

- Class to build a JFrame with label, textfield and button (MyFrame.java)
- Class with main to load the class with the JFrame (LoadFrame.java)
- Class MyHandler (MyHandler.java)

In my MyFrame I want to get the data from the textfield after I click the button, that value I want to pass to the class MyHandler and perform a calculation on the number I entered. I have not errors after writing the code, but on execution I get the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at EXTRA006.MyHandler.<init>(MyHandler.java:18)
at EXTRA006.MyFrame.<init>(MyFrame.java:36)
at EXTRA006.LoadFrame.main(LoadFrame.java:11)


Here is the main class:


Here is the class where I build my JFrame


And here is the class where I implement the ActionListener and perform the calculations.

 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The text field is empty when you first create it so you can't use the getText() method.

You must use the getText() method in the ActionListener.

So this mean you need to pass the text field (not the text) as a parameter to your ActionListener class.

Then in the actionPerformed() method you invoke the getText() method to get the current value of the text field. Then you can parse the text.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No surprises there.
When you invoke

the value of
is an empty string which is not a number.

One solution would be to pass your JFrame instance in the constructor of MyHandler. Later on in actionPerformed you can refer to the txtNumb via this instance, provided you have the correct getters.
 
Chris Green
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, I managed to solve the problem thanks to your inputs!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!