[英]Capitalize first letters in a Textfield in Java
這是可能的首字母大寫的文本字段
例如,用戶將鍵入“ hello”,並且“ Hello”將出現在文本字段中。
我對該代碼進行了罰款以大寫所有字母http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm
我嘗試將其編輯為僅大寫字母大寫,這是錯誤的
這是我的編輯
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
,更新text
的第一個字符
然后,您也許可以使用類似...
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.