javaswingjtextfielddocumentfilter

Capitalize first letters in a Textfield in Java


Is it to possible to capitalize the FIRST letter in a Textfield

E.g. The user would type 'hello' and 'Hello' would appear in the Textfield.

I fined this code to capitalize all letter http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm

and I try to edit it to capitalize only the FIRST letter put it is wrong

this is my edit

public class UppercaseDocumentFilter extends DocumentFilter {

public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.substring(0, 1).toUpperCase() + text.substring(1), attr);
  }

  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,AttributeSet attrs) throws BadLocationException {
    fb.replace(offset, length, text.substring(0, 1).toUpperCase() + text.substring(1), attrs);
  }

}

Solution

  • You're on the right direction, you might have a look at fb.getDocument().getLength() to determine the current length of the Document, when it's 0, update the first character of the text

    You might then be able to use something like...

    String text = "testing";
    StringBuilder sb = new StringBuilder(text);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    text = sb.toString();
    System.out.println(text);
    

    to capitalize the first character of the input text. You might want to do some other checks, but that's the basic idea

    Example

    Seems to work okay for me

    public class UppercaseDocumentFilter extends DocumentFilter {
    
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            if (fb.getDocument().getLength() == 0) {
                StringBuilder sb = new StringBuilder(text);
                sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
                text = sb.toString();
            }
            fb.insertString(offset, text, attr);
        }
    
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (fb.getDocument().getLength() == 0) {
                StringBuilder sb = new StringBuilder(text);
                sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
                text = sb.toString();
            }
            fb.replace(offset, length, text, attrs);
        }
    
    }