Creating a Text Field to Display and Edit a Number - Java Swing

Java examples for Swing:JTextField

Description

Creating a Text Field to Display and Edit a Number

Demo Code

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

public class Main {
  public static void main(String[] args) {
    JFormattedTextField tft1 = new JFormattedTextField(
        NumberFormat.getIntegerInstance());
    tft1.setValue(new Integer(123));

    Integer intValue = (Integer) tft1.getValue();

    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();
    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);/*from www.j  a  v a2s .  co  m*/
    tft3.setFormatterFactory(fmtFactory);

    // Retrieve the value from the text field
    BigDecimal bigValue = (BigDecimal) tft3.getValue();
  }
}

Related Tutorials