The integer argument to the JTextField constructor is actually the width in number of columns. From the docs:
public JTextField(int columns)
Constructs a new empty TextField with the specified number of columns. A default model is created and the initial string is set to null.
By constructing it with
ansTxt = new JTextField(5);
you'll basically get an empty text-field (slightly wider than if you constructed it using no-argument constructor). If you want it to contain the string "5" you should write
ansTxt = new JTextField("5");
Update:
IIRC, you'll get one event for keyDown, one for keyTyped, and one for keyUp. Presumably the text-field has not yet been updated on the keyDown event.
Either way I suggest that you encapsulate the Integer.parseInt in a
try { ... } catch (NumberFormatException e) { ... }
block since the user may very well write something else than an integer.
-->
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…