2017-04-03 32 views
0

這是可能的大寫FIRST信在一個文本框大寫的文本字段首字母在Java中

例如用戶會輸入'hello','Hello'會出現在Textfield中。

我被罰這個代碼能夠利用的所有信http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm

,我嘗試對其進行編輯以利用只有第一萊特 [R說得不對

這是我的編輯

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

} 

回答

1

你在正確的方向,你可以看看fb.getDocument().getLength()來確定Document的當前長度,當它是0時,更新f的text

IRST字符您也許然後可以使用類似...

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

大寫輸入text的第一個字符。你可能想要做一些其他的檢查,但是這是基本的想法

似乎爲我

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

} 
+0

感謝工作沒關係。我使用了fb.getDocument()。getLength()和這個我的更新if(fb.getDocument()。getLength()== 0){ fb.replace(offset,length,text.toUpperCase(),attrs); } else { fb.replace(offset,length,text,attrs); } – amirouche

+0

不,這不是我所建議的,而是將所有文本轉換爲大寫,如果用戶將文本粘貼到字段中會發生什麼?或者你調用'setText',你會使所有文本都變成大寫。 – MadProgrammer

+0

-_-,是的所有的文字大寫whene過去,我把你的第二個建議放到不工作。我是否可以在用戶試圖進入現場時調用任何方法? – amirouche