Hi All, just wondering how I get the keyboard input event for a JSpinner. I have already tried the Key adapter, but I don't seem to get any events for a key press, key released or key typed. It doesn't behave like a JTextField. Any ideas? Thanks. Sarone
Hi, What is your goal? You can use "aJSpinner.addChangeListener(chgLster)" to receive ChangeEvents whenever the current value in the JSpinner changes. You can retrieve the editor, used by the JSpinner to allow the user to type data directly, by "aJSpinner.getEditor()". It returns a JComponent that is an inner class of JSpinner. Its type depends on the SpinnerModel in use: JSpinner.ListEditor/.DateEditor/.NumberEditor/.DefaultEditor Then you can use "aDefaultEditor.getTextField()" to retrieve the JFormattedTextField used by the instance of DefaultEditor or subclass. I guess it's possible to receive KeyEvents by calling addKeyListener(kLster) on this JFormattedTextField.
Thanks so much Jose for your input, I'm trying to check the input as it is being typed in. I get changeEvent only when the input has changed, ie when the press the up or down arrow. Sometimes a user may want to type in the number in the textfield, and if its an invalid number I would like to pop up a message box saying valid numbers are between such and such. The JSpinner already changes the value back to the previous number if an invalid number is entered, provided you move to another component,- simply by clicking on another component. So your second suggestion for getting the KeyEvent to the embedded textfield is exactly what I'm after.(this is the best way right??- just checking :-)) - Sarone
What about preventing the focus to leave the JSpinner if the user typed something invalid? With an InputVerifier you can do that and, additionally, show a JOptionpane message informing the valid range. This is from the JFormattedTextField API:
Show a user message in the ParseException handler before returning false. Assign an instance of InputVerifier to the JFormattedTextField you extacted from the JSpinner with JComponent.setInputVerifier Tell me it it works.