[java]
package com.han;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* 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.
* @author HAN
*
*/
public class UpperCaseField extends JTextField {
/**
*
*/
private static final long serialVersionUID = 6854878572763032459L;
public UpperCaseField(int cols) {
// super() 可以被自動調用,但是有參構造方法並不能被自動調用,隻能依賴
// super關鍵字顯示地調用父類的構造方法
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = -4170536906715361215L;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return; www.aiwalls.com
}
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);
}
}
}
作者:Gaowen_HAN