import javax.swing.JTextField;
import javax.swing.text.Document;
/**
* 整数输入框</p>
*
* @author luojialin
* @since 2014-2-24
*/
public class IntegerTextField extends JTextField {
public IntegerTextField() {
this(new IntegerDocument(), null, 0);
}
public IntegerTextField(String text) {
this(new IntegerDocument(), text, 0);
}
public IntegerTextField(int columns) {
this(new IntegerDocument(), null, columns);
}
public IntegerTextField(String text, int columns) {
this(new IntegerDocument(), text, columns);
}
public IntegerTextField(Document doc, String text, int columns) {
super(doc,text,columns);
if(!(doc instanceof IntegerDocument))
throw new IllegalArgumentException("Document must be IntegerDocument");
}
}
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);
}
}