-1

I have a class with GUI components where user inputs numbers into JTextFields. I want to pass that values as int to another class(Ticket) in the same package where I will calculate a result using those 2 ints a return a String back to GUI class where it would be put into JLabel.

I can't get it to work. I was able to access a method from Ticket class in GUI class and print something in JLabel, but I can't pass those 2 values from JTextField to do the calculation.

halfer
  • 19,824
  • 17
  • 99
  • 186
zetbo
  • 78
  • 1
  • 6
  • Possible duplicate of [Convert JTextField input into an Integer](https://stackoverflow.com/questions/11071211/convert-jtextfield-input-into-an-integer) – Logan Apr 17 '18 at 19:15
  • 1
    A more specialized gui element may be more beneficial. Something like a JSpinner. Otherwise, you'd have to call `getText()` and convert it to an int manually using `Integer.parseInt(text)`. Of course that also will throw an exception if the user doesn't provide a valid number. – killjoy Apr 17 '18 at 19:36
  • I keep ketting NullPointerException on this line of code lblResult.setText(ticket.getAnswer()); On top of the class I have Ticket ticket; – zetbo Apr 17 '18 at 19:57
  • For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Apr 18 '18 at 02:39

1 Answers1

0

Lets say in GUI you have your JTextFields. Then in GUI you could have the following two methods which return the value of those JTextFields:

//return textfield 1
public int getTextFieldOne() {
    return Integer.parseInt(textField_one.getText());
}

//return textfield 2        
public int getTextFieldTwo() {
    return Integer.parseInt(textField_two.getText());
}

Then in your Ticket Class do the calculation by calling the above methods and then just call the setText() Method on your JLabel to set the result.

HoldTight
  • 205
  • 1
  • 2
  • 10
  • so in GUI class I would then add a method to put the result from Ticket class into JLabel like this one? labelRes.setText(tic.getRes()); I have declared Ticket tic at the top of my GUI class, and when I try this I get NullPointerException – zetbo Apr 18 '18 at 19:02
  • @zetbo Sorry for the late reply. But yes that should work. To debug try `System.out.print(tic.getRes())` in your GUI just to make sure your method is working. If this gives you the right result then your calculation methods are working fine and the problem lies elsewhere in the code. – HoldTight Apr 19 '18 at 20:49
  • @zetbo But I think Your error is most likely related to how you have initialised the JLabel and how you are using it. – HoldTight Apr 20 '18 at 08:59
  • I've managed to fix it. Seems like I forgot to put parameters in the method. Thank you for help anyway :) – zetbo Apr 20 '18 at 21:28