是否可以将文本字段中的FIRST字母大写
例如用户输入“hello”,“Hello”就会出现在文本字段中。
我将此代码罚款为将所有字母 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);
}
}
最佳答案
您的方向是正确的,您可以查看 fb.getDocument().getLength()
来确定 Document
的当前长度,当它是0
,更新文本
的第一个字符
然后您可能可以使用诸如...之类的东西
String text = "testing";
StringBuilder sb = new StringBuilder(text);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
text = sb.toString();
System.out.println(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);
}
}
关于java - Java 中文本字段中的首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195241/