I am saving items to JComboBox from a textfield(input) when a button is clicked. The user may give the input starting with lowerca开发者_如何学JAVAse but I want to change the first letter of the input to uppercase. How can I achieve this?
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:
MaskFormatter mf = new MaskFormatter("ULLLLLLLLL");
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 library offers a method in StringUtils
public static String capitalize(String str)
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!
精彩评论