JFormattedTextField intField1=new JFormattedTextField(NumberFormat.getIntegerInstance());
上面这个方法能实现是否是整型的输入,若要识别是否是double型应如何做,
NumberFormat中并没有getDoubleInstance这个方法.谢谢
上面这个方法能实现是否是整型的输入,若要识别是否是double型应如何做,
NumberFormat中并没有getDoubleInstance这个方法.谢谢
import javax.swing.text.*;
import java.awt.*;public class TextFieldTest extends JFrame
{
public TextFieldTest() {
setSize( 400,400 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); JTextField text = new JTextField();
text.setDocument( new NumberDocument(text) );
getContentPane().add( text,BorderLayout.NORTH ); setVisible( true );
} class NumberDocument extends PlainDocument
{
JTextField text = null;
double minRange = -Double.MAX_VALUE;
double maxRange = Double.MAX_VALUE; NumberDocument( JTextField text ) {
this.text = text;
} public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if( (null == str)|| ("".equals(str)) ) return; StringBuffer sb = new StringBuffer();
sb.append( text.getText() );
sb.insert( offs,str );
try{
double d = Double.parseDouble(sb.toString().trim());
if (d < minRange || d > maxRange){
throw new NumberFormatException();
}
else {
super.insertString( offs,str,a );
}
}catch (NumberFormatException ex){ Toolkit.getDefaultToolkit().beep();return; }
}
} public static void main( String args[] ) {
new TextFieldTest();
}
}