Accept BigDecimal from JFormattedTextField in Java

Description

The following code shows how to accept BigDecimal from JFormattedTextField.

Example


     //from  ww  w  .  java  2 s . c  om

import java.awt.BorderLayout;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;

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

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 f = new JFormattedTextField(new BigDecimal("123.4567"));
    DefaultFormatter fmt = new NumberFormatter(new DecimalFormat("#.0###############"));
    fmt.setValueClass(f.getValue().getClass());
    DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(fmt, fmt, fmt);
    f.setFormatterFactory(fmtFactory);

    BigDecimal bigValue = (BigDecimal) f.getValue();
    System.out.println(bigValue);

    frame.add(f, BorderLayout.NORTH);

    frame.add(new JTextField(), BorderLayout.SOUTH);
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Accept BigDecimal from JFormattedTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer