0

When I use setText() on the textfield it wont allow me to do so because what i want in there is an int, i would change the int to a string but int's are needed to do further calculations.

How can I get set the text of a JTextField with an int.

private void setAllTextFields(MenuItem m){
        desBox.setText(m.getDescriptions());
        priceTF.setText(m.getPrice());
        calsTF.setText(m.getCalories());
    }

price and calories are the numbers

thanks

mmuzahid
  • 2,252
  • 23
  • 42
SJ21W
  • 11
  • 3
  • 1
    You can `parse` a `String`...`Integer.parseInt("5");` – brso05 Apr 05 '16 at 12:20
  • 1
    You must display them as strings. You can always parse them back out to int to do calculations – OneCricketeer Apr 05 '16 at 12:21
  • sorted it now thanks for all the replies – SJ21W Apr 05 '16 at 12:35
  • @cricket_007 *"You must display them as strings. You can always parse them back out to int to do calculations"* Better still, use an int based `SpinnerNumberModel` in a `JSpinner` and keep the input/output values as integer! – Andrew Thompson Apr 05 '16 at 23:17
  • @AndrewThompson I'm not too well-versed in the Swing library, but would that work for a `JTextField`? I thought a Spinner was like a dropdown option. – OneCricketeer Apr 05 '16 at 23:22
  • *"I thought a Spinner was like a dropdown option."* That's a `JComboBox`. A spinner has little up/down arrows beside the field that allow the value to be incremented or decremented. For an example of what spinners look like (and how to use them) see [this answer](http://stackoverflow.com/a/17874718/418556).. – Andrew Thompson Apr 05 '16 at 23:25

2 Answers2

2

You could take number input using JFormattedTextField as follows:

JFormattedTextField numberField 
   = new JFormattedTextField(NumberFormat.getNumberInstance());

//get value from text field
double d = ((Number)numberField.getValue()).doubleValue();
mmuzahid
  • 2,252
  • 23
  • 42
1

You could parse each time you read the value :

// set :
priceTF.setText(String.valueOf(m.getPrice()));

// get :
int value = Integer.parseInt(priceTF.getText());
Apolo
  • 3,844
  • 1
  • 21
  • 51