Use DecimalFormat with JFormattedTextField in Java
Description
The following code shows how to use DecimalFormat with JFormattedTextField.
Example
import java.awt.BorderLayout;
import java.text.DecimalFormat;
import java.text.ParseException;
/*w ww . j av a2s .com*/
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(final String args[]) throws ParseException {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFormattedTextField tft2 = new JFormattedTextField(new DecimalFormat("#.0"));
tft2.setValue(new Float(123.43333F));
// Retrieve the value from the text field
Float floatValue = (Float) tft2.getValue();
System.out.println(floatValue);
frame.add(tft2, BorderLayout.NORTH);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »