2

A JSpinner is used to store a number in my application (with a SpinnerNumberModel).

As expected, the spinner doesn't allow invalid characters (letters, symbols, etc.) to be stored. However, those characters do appear in the spinner component when I type them in. As soon as I switch the focus to another component, they disappear.

Is there a way to prevent invalid characters from appearing in the spinner?

casperOne
  • 73,706
  • 19
  • 184
  • 253

1 Answers1

2

You can add a DocumentFilter to the editor of the spinner to prevent unwanted character from being added to the Document. You get the editor using code like:

JTextField editor = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();

Read the section from the Swing tutorial on Implementing a Document Filter for more information.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks for your response, but the getEditor method returns a JComponent, and there's no getTextField method in the JComponent class. Do I need to cast the returned JComponent to something else? –  Jun 09 '10 at 15:26
  • Yep, a cast was needed. **"JTextField editor = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField()"**. You should update your answer for future viewers. –  Jun 09 '10 at 15:33