62,614
社区成员
发帖
与我相关
我的任务
分享
public class UpperCaseTextField extends JTextField {
public UpperCaseTextField() {
super();
}
protected Document createDefaultModel() {
return new PlainDocument() {
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null || str == "")
return;
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str + oldString.substring(offs);
//if (newString.length() < 12) {
//super.insertString(offs, str.toUpperCase(), a);
//}
try{
Integer.parseInt(newString);
}catch{
return;
}
super.insertString(offs, str.toUpperCase(), a);
}
};
}
}
import java.awt.AWTEvent;
import java.awt.HeadlessException;
import java.awt.TextField;
import java.awt.event.KeyEvent;
public class NumberText extends TextField {
public NumberText() throws HeadlessException {
this.enableEvents(AWTEvent.KEY_EVENT_MASK);
}
public void processKeyEvent(KeyEvent e) {
if (e.getKeyCode() < KeyEvent.VK_0 || e.getKeyCode() > KeyEvent.VK_9) {
//如果为非数字,把文本框的最后一个字去掉后重新设置文本框不就OK了
this.setText(this.getText().substring(0, this.getText().length()));
}
}
}