数字:只能输入数值,backspace,del
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
//this class for monitoring keyTyped
public class KeyAction extends KeyAdapter{
public void keyTyped(KeyEvent e){
char ch=e.getKeyChar();
String detectStr;
//only 0 to 9 backspace or delete key character can be input
if(ch>0x2f&&ch<0x3a||ch==0x08||ch==0x10){
}else{
Toolkit.getDefaultToolkit().beep();
e.consume();//for consuming the listener
}
}//end of keyTyped
}//end of class长度: jtextfield.getDocument().addDocumentListener(...);
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
//this class for monitoring keyTyped
public class KeyAction extends KeyAdapter{
public void keyTyped(KeyEvent e){
char ch=e.getKeyChar();
String detectStr;
//only 0 to 9 backspace or delete key character can be input
if(ch>0x2f&&ch<0x3a||ch==0x08||ch==0x10){
}else{
Toolkit.getDefaultToolkit().beep();
e.consume();//for consuming the listener
}
}//end of keyTyped
}//end of class长度: jtextfield.getDocument().addDocumentListener(...);
最好的办法是继承一个PlainDocument类,:
下面是只可输入整数的类:
import javax.swing.text.*;
import java.awt.*;public class IntegerDocument extends PlainDocument
{ public void insertString(int index, String s, AttributeSet a)
throws BadLocationException { boolean noval = false; if ((s == null) || (s.length() == 0)) {
return;
} StringBuffer t = new StringBuffer(getLength() + s.length()); t.append(getText(0, index));
t.append(s);
t.append(getText(index, getLength() - index)); try {
Integer.parseInt(t.toString().trim());
} catch (NumberFormatException e) {
noval = true; if (noval) {
Toolkit.getDefaultToolkit().beep(); return;
}
} super.insertString(index, s, a);
}
}
import javax.swing.text.*;
import java.awt.*;
public class NumberDocument extends PlainDocument
{ /**
* Strip all non digit characters. '-' and '+' are only allowed as the
* first character. Only one '.' is allowed.
**/
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null) {
return;
} // Get current value
String curVal = getText(0, getLength());
boolean hasDot = curVal.indexOf(".")!=-1; // Strip non digit characters
char[] buffer = str.toCharArray();
char[] digit = new char[buffer.length];
int j = 0; if(offs==0 && buffer!=null && buffer.length>0 && buffer[0]=='-')
digit[j++] = buffer[0]; for (int i = 0; i < buffer.length; i++) {
if(Character.isDigit(buffer[i]))
digit[j++] = buffer[i];
if(!hasDot && buffer[i]=='.'){
digit[j++] = '.';
hasDot = true;
}
} // Now, test that new value is within range.
String added = new String(digit, 0, j);
try{
StringBuffer val = new StringBuffer(curVal);
val.insert(offs, added);
if(val.toString().equals(".") || val.toString().equals("-") || val.toString().equals("-."))
super.insertString(offs, added, a);
else{
Double.valueOf(val.toString());
super.insertString(offs, added, a);
}
}catch(NumberFormatException e){
// Ignore insertion, as it results in an out of range value
}
} public void setValue(double d){
try{
remove(0, getLength());
insertString(0, (new Double(d)).toString(), null);
}catch(BadLocationException e){
// Will not happen because we are sure
// we use the proper range
}
} public double getValue(){
try{
String t = getText(0, getLength());
if(t != null && t.length() > 0){
return Double.parseDouble(t);
}
else{
return 0;
}
}catch(BadLocationException e){
// Will not happen because we are sure
// we use the proper range
throw new Error();
}
}
jtextfield.setDocument(new IntegerDocument());
如果你要限制它的长度,自己改吧,不用我教了吧:)
可以固定格式输入,使用比如日期
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
DateFormatter df = new DateFormatter(format);
JFormattedTextField ftf1 = new JFormattedTextField(df);
数字则用NumberFormat,其它固定格式比如
MaskFormatter mf2 = new MaskFormatter(“(###) ###-####”);
JFormattedTextField ftf3 = new JFormattedTextField(mf2)
如果不是的话,
JTextField jtxt = new JTextField();
jtxt.setDocument(new JNumberDocument(maxlength, declength));
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: Acylas</p>
* @author Acylas
* @version 1.0
*/
private class JNumberDocument extends PlainDocument {
private int maxlength;
private int declength; public JNumberDocument() {
this(16, 0);
}
public JNumberDocument(int declength) {
this(16, declength);
}
public JNumberDocument(int maxlength, int declength) {
this.maxlength = maxlength;
this.declength = declength;
} public void insertString(int offset, String value, AttributeSet attr)
throws BadLocationException {
try {
Number nb = df.parse(getText(0, offset) + value + getText(offset, getLength() - offset));
value = df.format(nb);
}
catch (Exception e) {
// e.printStackTrace();
return;
}
// int decPos = str.indexOf(".");
// if (s.equals("F") || s.equals("f") || s.equals("D") || s.equals("d")
// || (str + s).length() > maxlength
// || (decPos > -1 && offset > decPos && ((str.substring(decPos + 1)) + s).length() > declength)
// || (str.trim().equals("0") && !s.substring(0, 1).equals(".") && offset != 0)
// || (s.equals(".") && declength == 0)
// || (s.indexOf(".") > -1 && s.substring(s.indexOf(".") + 1).length() > declength)) {
// /**发出错误提示音*/
// Toolkit.getDefaultToolkit().beep();
// return;
// }
// super.remove(0, super.getLength());
//屏蔽事件
javax.swing.event.DocumentListener[] listener = super.getDocumentListeners();
if (listener != null) {
for (int i=0; i<listener.length; i++)
super.removeDocumentListener(listener[i]);
}
super.remove(0, getLength());
if (listener != null) {
for (int i=0; i<listener.length; i++)
super.addDocumentListener(listener[i]);
}
super.insertString(0, value, attr);
JNumberField.this.setSelectionStart(offset + 1);
JNumberField.this.setSelectionEnd(offset + 1);
}
}
JNumberField.this.setSelectionStart(offset + 1);
JNumberField.this.setSelectionEnd(offset + 1);
这两句怎么回事,JNumberField类怎么获得
private JTextField jtxt;
public JNumberDocument(JTextField jtxt) {
this(jtxt, 16, 0);
}
public JNumberDocument(JTextField jtxt, int declength) {
this(jtxt,16, declength);
}
public JNumberDocument(JTextField jtxt, int maxlength, int declength) {
this.jtxt = jtxt;
this.maxlength = maxlength;
this.declength = declength;
}.....
jtxt.setSelectionStart(offset + 1);
jtxt.setSelectionEnd(offset + 1);
.....