SJ21W
SJ21W

Reputation: 11

Cant set a JTextField as an int

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

Upvotes: 0

Views: 291

Answers (2)

mmuzahid
mmuzahid

Reputation: 2270

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();

Upvotes: 2

Apolo
Apolo

Reputation: 4050

You could parse each time you read the value :

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

// get :
int value = Integer.parseInt(priceTF.getText());

Upvotes: 1

Related Questions