简体   繁体   English

JFormattedTextField-如何只允许使用字符?

[英]JFormattedTextField - How to allow only chars?

I've got an ArrayList of Characters and I've also got a JTextField which returns a String. 我有一个字符的ArrayList,还有一个返回字符串的JTextField。 I was wondering how do I only permit chars to be entered? 我想知道如何只允许输入字符吗? Or perhaps how could I only allow the first letter of the string to get passed? 也许我怎么只允许字符串的第一个字母通过?

So you only want to allow certain chars to be entered, chars that are held by an ArrayList? 因此,您只想允许输入某些字符,即由ArrayList保留的字符? If so, I'd use a JTextField and then add a DocumentFilter to its Document. 如果是这样,我将使用JTextField,然后将DocumentFilter添加到其Document中。


Edit 编辑
Based on your comment: 根据您的评论:

I want the input to be of type Character. 我希望输入的字符类型。 By default I can type in 'a' into my JTextField and it will come out as type String whereas I want it to be of type Character. 默认情况下,我可以在JTextField中输入“ a”,它将以String类型出现,而我希望它是Character类型。 So If I have a method that passes in a char, and I try and pass in a String it doesn't work and I need it to be a char instead. 因此,如果我有一个传递字符的方法,而我尝试传递一个字符串,则该方法不起作用,我需要将其作为字符。

You've got an XY Problem here meaning your barking up the wrong tree and looking for the wrong solution, an impossible and illogical one. 您这里有一个XY问题,这意味着您将吠叫错误的树并寻找错误的解决方案,这是不可能且不合逻辑的解决方案。 A JTextField will always hold Strings. JTextField将始终包含字符串。 Just get the char array from the String, charArray() and then use it. 只需从String charArray()获取char数组,然后使用它即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM