The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JFormattedTextField  [3 examples]

e995. Creating a Text Field to Display and Edit a Number

This example uses a JFormattedTextField to allow the display and editing of a number. By default, when the component loses the focus and the modified value is a valid date, the modified value is saved. Otherwise, if the modified value is not a valid date, the modified value is discarded and the old value is displayed.
    // Support an integer number; if a decimal point is typed,
    // the decimal point and all following characters are discarded
    JFormattedTextField tft1 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    tft1.setValue(new Integer(123));
    
    // Retrieve the value from the text field
    Integer intValue = (Integer)tft1.getValue();
    
    
    // Support a decimal number with one digit following the decimal point;
    // if more digits after the decimal point is typed, the value is rounded to one decimal place
    JFormattedTextField tft2 = new JFormattedTextField(new DecimalFormat("#.0"));
    tft2.setValue(new Float(123.4F));
    
    // Retrieve the value from the text field
    Float floatValue = (Float)tft2.getValue();
By default, if the type of the value is not one of Byte, Short, Integer, Long , Float, or Double, the object is automatically converted to a Double after it has been edited. To prevent this, a custom formatter must be used. This example demonstrates this by using a BigDecimal object.
    // Support a decimal number with arbitrary number of decimal digits.
    // Actually, this isn't technically possible using DecimalFormat;
    // the best that we can do is to specify lots of #'s
    JFormattedTextField tft3 = new JFormattedTextField(new BigDecimal("123.4567"));
    DefaultFormatter fmt = new NumberFormatter(new DecimalFormat("#.0###############"));
    fmt.setValueClass(tft3.getValue().getClass());
    DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(fmt, fmt, fmt);
    tft3.setFormatterFactory(fmtFactory);
    
    // Retrieve the value from the text field
    BigDecimal bigValue = (BigDecimal)tft3.getValue();

 Related Examples
e996. Creating a Text Field to Display and Edit a Date
e997. Creating a Text Field to Display and Edit a Phone Number

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JTextArea    JTextComponent    JTextField    JTextPane    Styles   


© 2002 Addison-Wesley.