I have made a JFormattedTextField
that is formatted to only take numbers:
Number num;
JFormattedTextField Length = new JFormattedTextField(num);
Now I want to get the number out of that and multiply it by 23
. I know you can do:
String LengthStr = Length.getText();
int LengthInt = Integer.parseInt(LengthStr);
int Total = LengthInt*23;
But Isn't there an easier way? I've tried:
int LengthInt = Length.getText();
int Total = LengthInt * 23;
because it should be a number already.
The above didn't work because it says
Required: int Found: String
What I 'm asking for is that if the JFormattedTextField
is formatted to be an int
, then surely I can do something like
int LengthInt = Length.getInt();
int Total = LengthInt *23;
No, you can't. The line: int LengthInt = Length.getText();
tries to put a String Object (Length.getText()
) into an primitive tipe (int
).
There is no implicit conversion from String to integer in Java, because a String can contain anything (like "abc", for example) that is not directly convertible to a number.
Also, the first two lines should be changed to this: JFormattedTextField Length = new JFormattedTextField(NumberFormat.getIntegerInstance());
Instantiate the JFormattedTextField with the NumberFormat instead of Number.