无法将JTextField设置为int

时间:2016-04-05 12:18:28

标签: java swing casting jtextfield

当我在文本字段上使用setText()时,它不允许我这样做,因为我想要的是int,我会将int更改为字符串,但需要int来进一步计算

如何设置JTextField int的文字。

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

价格和卡路里是数字

感谢

2 个答案:

答案 0 :(得分:2)

您可以使用JFormattedTextField进行数字输入,如下所示:

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

//get value from text field
double d = ((Number)numberField.getValue()).doubleValue();

答案 1 :(得分:0)

每次读取值时都可以解析:

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

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