I'm new to java and I have tried a lot in converting strings placed in a JTextField
Component into an integer type, but I couldn't. So kindly help me with this problem.
Asked
Active
Viewed 124 times
-1

Mariano D'Ascanio
- 1,202
- 2
- 16
- 17

user3865748
- 51
- 4
-
1But... JTextField isn't an Integer. What are you trying to achieve? – Halvor Holsten Strand Jul 22 '14 at 17:52
-
@Ondkloss This is one more case of a badly redacted question where the title has more information than the post. He is referring to the string in the JTextField and not the JTextField itself. – DSquare Jul 22 '14 at 17:54
-
btw, next time use [Google like this](https://www.google.com.mx/search?client=ubuntu&channel=fs&q=convert+string+to+jtextfield&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=n6bOU7fQFMXB8AHLvYCwAg#channel=fs&q=convert+string+jtextfield+to+int) and that could lead you to: [Convert JTextField Input to Integer](http://stackoverflow.com/questions/11071211/convert-jtextfield-input-into-an-integer). – Frakcool Jul 22 '14 at 18:01
-
On Execution i'll enter an integer in the JTextField and i need to process the entered integer later in the code... – user3865748 Jul 22 '14 at 18:06
-
Look at both answers below, also check both links I gave (if you haven't done that), if you need better help please post a [MCVE](http://stackoverflow.com/help/mcve) – Frakcool Jul 22 '14 at 18:07
-
For the sake of common sense, use a `JSpinner` with `SpinnerNumberModel` instead. – Andrew Thompson Jul 23 '14 at 02:29
2 Answers
1
Try the Integer.parseInt(java.lang.String) method.
int i;
try {
i = Integer.parseInt(testField.getText()).intValue();
}
catch (NumberFormatException ex) {
// FIXME Handle your exception!
}

Alex Barker
- 4,316
- 4
- 28
- 47
0
I guess you're trying to parse the String got from the user input on JTextField
and not the JTextField
at all, so it should be something like this.
JTextField myTextField = new JTextField();
String textFromTextField = myTextField.getText();
int number = Integer.parseInt(textFromTextField);
System.out.println(number);

Frakcool
- 10,915
- 9
- 50
- 89