How to limit a JTextArea to only accept a legal set of characters?

五迷三道 提交于 2019-12-31 01:43:14

问题


Anybody know if there is an easy way to limit the allowed characters for a JTextArea. I.e. similar to JTextField using MaskFormatter.

Specifically I want to limit the allowed characters for a JTextArea to only uppercase characters and only a very limited set characters like !"#¤%&/()=


回答1:


Implement a javax.swing.text.DocumentFilter to remove inappropriate characters. Set that on your favourite AbstractDocument and construct you JTextArea with that.




回答2:


You may find the concept of Chaining Document Filters interesting. The first filter would automatically convert lower case characters to upper case (included in above link) so the user doesn't have to worry about this, then the second filter would validate all the characters (you would need to write your own).




回答3:


Try to extend PlainDocument and change the method insertString() to filter out all unwanted characters and replace lower with uppercase letters. Then you can use this special document in your JTextArea.




回答4:


You can assign a filter to JTextArea document. Just override the method insertString in the class DocumentFilter to ignore the characters



来源:https://stackoverflow.com/questions/1629961/how-to-limit-a-jtextarea-to-only-accept-a-legal-set-of-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!