开发者

Java JSpinner Prevent Letter Insertion

开发者 https://www.devze.com 2023-01-02 16:56 出处:网络
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 ch

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 c开发者_开发知识库omponent, they disappear.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号