Customized fields can easily be created by extending the model and changing the default model provided. For example, the following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard or it is altered via programmatic changes.
public class UpperCaseField extends JTextField {
public UpperCaseField(int cols) {
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] upper = str.toCharArray();
for (int i = 0; i < upper.length; i++) {
upper[i] = Character.toUpperCase(upper[i]);
}
super.insertString(offs, new String(upper), a);
}
}
}
# 1 楼答案
提供:JTextField
# 2 楼答案
试一试
# 3 楼答案
您可以处理文本字段的on key up事件,并将文本重置为toUpperCase
这里显示了一种更好的方法
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JTextField.html
# 4 楼答案
定义一个
DocumentFilter
并分配给JTextFiled
的Document
或只是扩展JTextField
中使用的PlainDocument
并重写insertString()
方法。将字符串参数转换为大写并传递给super.insertString()