hemanth kumar
hemanth kumar

Reputation: 3078

Change the first letter of a word to uppercase in java

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?

Upvotes: 0

Views: 1733

Answers (3)

camickr
camickr

Reputation: 324147

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");

Upvotes: 6

Alex Gitelman
Alex Gitelman

Reputation: 24732

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!

Upvotes: 2

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.

Upvotes: 3

Related Questions