2017-04-03 26 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