Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Convert First Letter of String to Uppercase for each word.

807601May 20 2008 — edited May 22 2008
Hello everyone.

I'm writing a program that take a String in a TextField. I would like all the first letter of all the words put into that textfield to be converted to uppercase letters.

i.e input = "i'm super cool" would become input = "I'm Super Cool"

I've been messing with it for hours and can get it to String the first letters properly to uppercase but it adds the formatted string to the end of the lowercase String. I hope I'm making any sense at all. I've only been doing JAVA for about a year now so please excuse the newbie code
	public class TextFormatter {

public static void firstLetterToUppercase(JTextField textField) {
	String text = textField.getText();
	StringBuffer result = new StringBuffer(text);
	char ch;
	for (int i = 0; i < text.length(); i++) {
		ch = text.charAt(i);
		if (Character.isLetter(ch)
				&& ((i == 0) || !Character.isLetter(text.charAt(i - 1)))){
			result.append(Character.toUpperCase(ch));
		} else {
			result.append(Character.toLowerCase(ch));
		}
	}
	textField.setText(text);
	textField.setText(result.toString());
};

private static Component test() {
	final JTextField jtf = new JTextField("devin the great");
	jtf.addFocusListener(new FocusAdapter() {
		@Override
		public void focusLost(FocusEvent e) {
			firstLetterToUppercase(jtf);
		}
	});

	return jtf;
}

private static Component test2() {
	final JTextField jtf = new JTextField("blank");

	return jtf;
}

public static void main(String[] args) {
	JFrame mainFrame = new JFrame();
	mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	JPanel mainPanel = new JPanel(new BorderLayout());

	mainPanel.add(test(), BorderLayout.CENTER);
	mainPanel.add(test2(), BorderLayout.SOUTH);
	mainFrame.add(mainPanel);
	mainFrame.pack();
	mainFrame.setVisible(true);
}
I'm eventually going to exclude certain words (such as "and", "the", "of", etc.) from being converted to uppercase but I believe I can figure that one out by myself.

Thanks much for your help!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 19 2008
Added on May 20 2008
13 comments
4,154 views