java中将单词的第一个字母更改为大写
单击按钮时,我将文本字段(输入)中的项目保存到 JComboBox。用户可能会以小写开头输入,但我想将输入的第一个字母更改为大写。我怎样才能实现这个目标?
I am saving items to JComboBox from a textfield(input) when a button is clicked. The user may give the input starting with lowercase but I want to change the first letter of the input to uppercase. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将文档过滤器添加到将第一个字符转换为大写的文本字段当它被输入到文本字段中时。
当然,您还需要处理第一个字符被删除的情况。
单击“保存”按钮时进行转换还需要做一些工作,但这样用户可以在键入时和保存到组合框之前看到大写字符。
或者,如果文本字段有最大大小,您可以使用带有掩码的 JFormattedTextField。像这样的东西:
Add a Document Filter to the text field that converts the first character to upper case as it is entered into the text field.
Of course you would also need to handle the case when the first character is deleted.
A little more work then doing the converstion when the "Save" button is clicked but this way the use sees the upper cased character as it is typed and before it is saved to the combo box.
Or if the text field has a maximum size you could use a JFormattedTextField with a mask. Something like:
接受输入。创建一个由两部分组合组成的新字符串。第一部分是仅包含第一个字符的子字符串,然后您可以对其调用 toUpperCase(),第二部分是从第二个字符开始的子字符串。
这应该可以实现你想要的。
Take the input. Create a new string consisting of the combination of two parts. The first part is the substring only consisting of the first character, which you then call toUpperCase() on, and the second part is the substring starting with the second character.
This should accomplish what you want.
Apache Commons Lang 库在
StringUtils
中提供了一种方法,可以完全满足您的需要。
http://commons.apache.org/lang/api-2.6/index.html
它还有许多其他有用的方法。
请不要自己实施!
Apache Commons Lang library offers a method in
StringUtils
that does exactly what you need.
http://commons.apache.org/lang/api-2.6/index.html
It also has many other useful methods.
Please, don't implement it yourself!