JFormattedTextField - DecimalFormat

Hi.
I have a problem with JFormattedTextField.
I'm using this with an DecimalFormat with pattern ######0.00#####
JFormattedTextField = new JFormattedTextField(new DecimalFormat("<pattern>"));
Now when I enter a minus sign '-' as first charachter this is ignored and the text in the field is 0.00
I have tried using a negitive subpattern so the pattern is like
######0.00#####;-#####0.0######
But it doesn't work....
Help Please!!

Try using a MaskFormatter.

Similar Messages

  • Jformattedtextfield/decimalformat - set number of digits

    hi everybody,
    i am using a jformattedtextifield and applying a decimalformat with patter "00.00" but when i am setting the value to 1234.1234 its still valid.
    i only want to have 12.12 as a valid value or any value with 2 digits befor and 2 digits after the dot.
    greets
    lukas

    Try using a MaskFormatter.

  • Tricky behaviour on JFormattedTextField

    Dear friends,
    after few trials using JFormattedTextField, I finaly figured out how it beaves...
    if you have te value 1,00 and type DEL with the cursor just before the comma character, the text field value becomes 100,00 - this weird behaviour has a simple explanation: when you click DEL before the comma symbol, the text component remove the comma, and the value 1,00 becomes 100. After that, the view formatter add the comma again and the value becomes 100,00. Strange ? yes, very strange behaviour... at least from the point of view of the user. My user is asking me: "Why 1 dolar becomes a hundred dollars in a unique touch?"
    my question now is: How can I avoid that behaviour ? <b>how can I avoid the value 1,00 to be transformed into 100,00 by clicking DEL before the comma?</b> is it possible ?
    below is my test code:
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.math.BigDecimal;
    import java.text.DecimalFormat;
    import java.text.DecimalFormatSymbols;
    import java.util.Locale;
    import javax.swing.JButton;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.NumberFormatter;
    public class testeFormat {
         public static JLabel getText = new JLabel("getText  = ");
         public static JLabel getValue = new JLabel("getValue = ");
         public static void main(String args[]) {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().setLayout(new GridLayout(4, 1));
              final JFormattedTextField tf = new JFormattedTextField();
              DecimalFormat df = new DecimalFormat("#,###.00");
              df.setDecimalFormatSymbols(new DecimalFormatSymbols(new Locale("pt", "BR")));
              NumberFormatter nf = new NumberFormatter(df);
              nf.setValueClass(BigDecimal.class);
              nf.setOverwriteMode(false);
              DefaultFormatterFactory factory = new DefaultFormatterFactory(
                        //new NumberFormatter(df), // Default
                        nf, // Display
                        nf); // Edit
              tf.setFormatterFactory(factory);
              tf.setHorizontalAlignment(SwingConstants.RIGHT);
              nf.setAllowsInvalid(false);
              tf.setValue(new Double(0.0d));
              tf.setColumns(20);
              frame.getContentPane().add(tf);
              JButton button = new JButton("Test");
              frame.getContentPane().add(button);
              frame.getContentPane().add(getText);
              frame.getContentPane().add(getValue);
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        getText.setText("getText() = " + tf.getText());
                        getValue.setText("getValue() = " + tf.getValue());
              frame.setSize(new Dimension(300, 200));
              frame.setVisible(true);
    }

    you could add a keyListener
        tf.addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            if(ke.getKeyCode() == KeyEvent.VK_DELETE)
              if(tf.getText().charAt(tf.getCaretPosition()) == ',')
                ke.consume();
                java.awt.Toolkit.getDefaultToolkit().beep();
            }}});

  • Formatting using JFormattedTextField

    Hi everyone , I'm trying to create a JFormattedTextField wich accepts only number and have a limited size and if the user didn't fill all field, I want this fields stillValid..
    JFormattedTextField fmtNumer = new JFormattedTextField(new MaskFormatter("###,###");
    Thanks.

    Set the format using a DecimalFormat. Set the document to be one that allows a limited size.
    public class DocumentSizeFilter extends DocumentFilter {
          * Allows unlimited text.
         public static final int UNLIMITED_TEXT = -1;
                   private int maxCharacters;
        private boolean DEBUG = false;
         * Default constructor. Does not limit size of document.
        public DocumentSizeFilter() {
           this(UNLIMITED_TEXT);
         * Constructor
         * @param maxChars the maximum number of characters to allow
        public DocumentSizeFilter(int maxChars) {
            maxCharacters = maxChars;
         //     ------------------------  Methods ---------------------------
         * Set the maximum number of characters allowed.
         * <B>UNLIMITED_TEXT<\B> specified unlimited text size.
         * @param maxChars the maximum number of characters to allow
        public void setMaxSize (int maxChars) {
            maxCharacters = maxChars;
        public void insertString(FilterBypass fb, int offs,
                                 String str, AttributeSet a)
            throws BadLocationException {
            if (DEBUG) {
                System.out.println("in DocumentSizeFilter's insertString method");
            //This rejects the entire insertion if it would make
            //the contents too long. Another option would be
            //to truncate the inserted string so the contents
            //would be exactly maxCharacters in length.
            if (maxCharacters == UNLIMITED_TEXT ||
                      (fb.getDocument().getLength() + str.length()) <= maxCharacters)
                super.insertString(fb, offs, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
        public void replace(FilterBypass fb, int offs,
                            int length,
                            String str, AttributeSet a)
            throws BadLocationException {
            if (DEBUG) {
                System.out.println("in DocumentSizeFilter's replace method");
            //This rejects the entire replacement if it would make
            //the contents too long. Another option would be
            //to truncate the replacement string so the contents
            //would be exactly maxCharacters in length.
            if (maxCharacters == UNLIMITED_TEXT ||
                      (fb.getDocument().getLength() + str.length()
                 - length) <= maxCharacters)
                super.replace(fb, offs, length, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
              textFilter = new DocumentSizeFilter(/*num characters to allow*/);
              AbstractDocument doc;
              Document doci = getDocument();
              if (doci instanceof AbstractDocument) {
                   doc = (AbstractDocument) doci;
                   doc.setDocumentFilter(textFilter);
              }

  • Selection problem with JFormattedTextField

    I encounter a problem to select the content of a JFormattedTextField.
    Here is a class for a dialog containing 2 JFormattedTextFields :
    * Created on 7 juin 2005
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package cimpa.smartndtkit.dialog;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.text.DecimalFormat;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import cimpa.smartndtkit.utilities.Texts;
    import cimpa.smartndtkit.utilities.basic_classes.MyButton;
    import cimpa.smartndtkit.utilities.basic_classes.MyFormattedTextField;
    import cimpa.smartndtkit.utilities.basic_classes.MyLabel;
    import cimpa.smartndtkit.utilities.basic_classes.MyPanel;
    * @author st08051
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class ChangePaletteLimitsDialog extends MyDialog {
         private boolean isOK = false;
         private float minValue, maxValue;
         private MyButton bOK, bCancel;
         private MyFormattedTextField txtMin, txtMax;
         public ChangePaletteLimitsDialog(JFrame parent, float minValue, float maxValue){
              super(parent, "Modification des limites", true);
              setResizable(false);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              getContentPane().setLayout(new GridBagLayout());
              /** Constantes */
              Insets leftComponentInsets = new Insets(15,30,0,5);
              Insets rightComponentInsets = new Insets(15,5,0,30);
              Insets buttonsInsets = new Insets(8,5,8,5);
              int txtWidth = 60;
              int txtHeight = 22;
              DecimalFormat format = Texts.formatFactory("###0.###");
              /** Cr�ation des composants */
              MyLabel labelMin = new MyLabel("Valeur minimale :");          
              txtMin = new MyFormattedTextField(format);
              txtMin.setHorizontalAlignment(JTextField.RIGHT);
              txtMin.setAlignmentX(JTextField.RIGHT_ALIGNMENT);
              txtMin.setSizes(txtWidth, txtHeight);
              txtMin.setText(""+minValue);
    //          txtMin.setValue(new Float(minValue));
              txtMin.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent ke) {
                        keyPressed_actionPerformed(ke);
              txtMin.addFocusListener(new FocusAdapter() {
                   public void focusGained(FocusEvent arg0) {
                        txtMin.selectAll();
    //               public void focusLost(FocusEvent arg0) {
    //          txtMin.addActionListener(new ActionListener() {
    //               public void actionPerformed(ActionEvent arg0) {
    //                    txtMin.selectAll();
              MyLabel labelMax = new MyLabel("Valeur maximale :");
              txtMax = new MyFormattedTextField(format);
              txtMax.setHorizontalAlignment(JTextField.RIGHT);
              txtMax.setAlignmentX(JTextField.RIGHT_ALIGNMENT);
              txtMax.setSizes(txtWidth, txtHeight);
              txtMax.setText(""+maxValue);
    //          txtMax.setValue(new Float(maxValue));
              txtMax.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent ke) {
                        keyPressed_actionPerformed(ke);
              txtMax.addFocusListener(new FocusAdapter() {
                   public void focusGained(FocusEvent arg0) {
                        txtMax.selectAll();
    //               public void focusLost(FocusEvent arg0) {
    //          txtMax.addActionListener(new ActionListener() {
    //               public void actionPerformed(ActionEvent arg0) {
    //                    txtMax.selectAll();
              MyPanel panel = new MyPanel();
              bOK = new MyButton("OK");
              bOK.setSizes(60,25);
              bOK.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        bOK_actionPerformed();
              bCancel = new MyButton("Annuler");
              bCancel.setSizes(60,25);
              bCancel.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        bCancel_actionPerformed();
              /** Contraintes */
              GridBagConstraints constraints = new GridBagConstraints();
              constraints.anchor = GridBagConstraints.CENTER;
              /** Agencement des composants */
              constraints.gridx = 1;
              constraints.gridy = 0;
              constraints.gridwidth = 2;
              constraints.insets = leftComponentInsets;
              getContentPane().add(labelMin, constraints);
              constraints.gridx = 3;
              constraints.insets = rightComponentInsets;
              getContentPane().add(txtMin, constraints);
              constraints.gridx = 1;
              constraints.gridy = 1;
              constraints.insets = leftComponentInsets;
              getContentPane().add(labelMax, constraints);
              constraints.gridx = 3;
              constraints.insets = rightComponentInsets;
              getContentPane().add(txtMax, constraints);
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.gridwidth = 1;
              constraints.insets = buttonsInsets;
              panel.add(bOK, constraints);
              constraints.gridx = 1;
              panel.setLayout(new GridBagLayout());
              panel.add(bCancel, constraints);
              constraints.gridx = 0;
              constraints.gridy = 3;
              constraints.gridwidth = 6;
              constraints.anchor = GridBagConstraints.CENTER;
              getContentPane().add(panel, constraints);
              this.pack();
              setLocationRelativeTo(parent);
              txtMin.requestFocus();
    //          getRootPane().setDefaultButton(bOK);
              setVisible(true);
          * @return
         public boolean isOK() {
              return isOK;
         public void bOK_actionPerformed(){
              isOK=true;
              minValue = new Float(txtMin.getText()).floatValue();
              maxValue = new Float(txtMax.getText()).floatValue();
              dispose(); //st11870 : � faire en dehors ou l�?
         public void bCancel_actionPerformed(){
              escapeActionPerformed();
         private void keyPressed_actionPerformed(KeyEvent ke) {
              if (ke.getKeyChar() == KeyEvent.VK_ESCAPE) {
                   escapeActionPerformed();
              else if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
                   bOK_actionPerformed();
         protected void escapeActionPerformed() {
              isOK=false;
              dispose();
         public float getMaxValue() {
              return maxValue;
         public float getMinValue() {
              return minValue;
    }The problem is that the first time I pass through a textfield, it selects its content. But once, it has been selected, it can't be selected anymore...
    And if I make a setValue() during the initialization, it cannot be selected at all!
    Does anyone know how to fix this?
    Thanks!

    Should work now...
    package cimpa.smartndtkit.dialog;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.text.DecimalFormat;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class ChangePaletteLimitsDialog extends JDialog {
         private boolean isOK = false;
         private float minValue, maxValue;
         private JButton bOK, bCancel;
         private JFormattedTextField txtMin, txtMax;
         public ChangePaletteLimitsDialog(JFrame parent, float minValue, float maxValue){
              super(parent, "Modification des limites", true);
              setResizable(false);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              getContentPane().setLayout(new GridBagLayout());
              /** Constantes */
              Insets leftComponentInsets = new Insets(15,30,0,5);
              Insets rightComponentInsets = new Insets(15,5,0,30);
              Insets buttonsInsets = new Insets(8,5,8,5);
              int txtWidth = 60;
              int txtHeight = 22;
              DecimalFormat format = formatFactory("###0.###");
              /** Cr�ation des composants */
              JLabel labelMin = new JLabel("Valeur minimale :");          
              txtMin = new JFormattedTextField(format);
              txtMin.setHorizontalAlignment(JTextField.RIGHT);
              txtMin.setAlignmentX(JTextField.RIGHT_ALIGNMENT);
              txtMin.setSize(txtWidth, txtHeight);
              txtMin.setText(""+minValue);
    //          txtMin.setValue(new Float(minValue));
              txtMin.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent ke) {
                        keyPressed_actionPerformed(ke);
              txtMin.addFocusListener(new FocusAdapter() {
                   public void focusGained(FocusEvent arg0) {
                        txtMin.selectAll();
    //               public void focusLost(FocusEvent arg0) {
    //          txtMin.addActionListener(new ActionListener() {
    //               public void actionPerformed(ActionEvent arg0) {
    //                    txtMin.selectAll();
              JLabel labelMax = new JLabel("Valeur maximale :");
              txtMax = new JFormattedTextField(format);
              txtMax.setHorizontalAlignment(JTextField.RIGHT);
              txtMax.setAlignmentX(JTextField.RIGHT_ALIGNMENT);
              txtMax.setSize(txtWidth, txtHeight);
              txtMax.setText(""+maxValue);
    //          txtMax.setValue(new Float(maxValue));
              txtMax.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent ke) {
                        keyPressed_actionPerformed(ke);
              txtMax.addFocusListener(new FocusAdapter() {
                   public void focusGained(FocusEvent arg0) {
                        txtMax.selectAll();
    //               public void focusLost(FocusEvent arg0) {
    //          txtMax.addActionListener(new ActionListener() {
    //               public void actionPerformed(ActionEvent arg0) {
    //                    txtMax.selectAll();
              JPanel panel = new JPanel();
              bOK = new JButton("OK");
              bOK.setSize(60,25);
              bOK.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        bOK_actionPerformed();
              bCancel = new JButton("Annuler");
              bCancel.setSize(60,25);
              bCancel.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        bCancel_actionPerformed();
              /** Contraintes */
              GridBagConstraints constraints = new GridBagConstraints();
              constraints.anchor = GridBagConstraints.CENTER;
              /** Agencement des composants */
              constraints.gridx = 1;
              constraints.gridy = 0;
              constraints.gridwidth = 2;
              constraints.insets = leftComponentInsets;
              getContentPane().add(labelMin, constraints);
              constraints.gridx = 3;
              constraints.insets = rightComponentInsets;
              getContentPane().add(txtMin, constraints);
              constraints.gridx = 1;
              constraints.gridy = 1;
              constraints.insets = leftComponentInsets;
              getContentPane().add(labelMax, constraints);
              constraints.gridx = 3;
              constraints.insets = rightComponentInsets;
              getContentPane().add(txtMax, constraints);
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.gridwidth = 1;
              constraints.insets = buttonsInsets;
              panel.add(bOK, constraints);
              constraints.gridx = 1;
              panel.setLayout(new GridBagLayout());
              panel.add(bCancel, constraints);
              constraints.gridx = 0;
              constraints.gridy = 3;
              constraints.gridwidth = 6;
              constraints.anchor = GridBagConstraints.CENTER;
              getContentPane().add(panel, constraints);
              this.pack();
              setLocationRelativeTo(parent);
              txtMin.requestFocus();
    //          getRootPane().setDefaultButton(bOK);
              setVisible(true);
          * @return
         public boolean isOK() {
              return isOK;
         public void bOK_actionPerformed(){
              isOK=true;
              minValue = new Float(txtMin.getText()).floatValue();
              maxValue = new Float(txtMax.getText()).floatValue();
              dispose();
         public void bCancel_actionPerformed(){
              escapeActionPerformed();
         private void keyPressed_actionPerformed(KeyEvent ke) {
              if (ke.getKeyChar() == KeyEvent.VK_ESCAPE) {
                   escapeActionPerformed();
              else if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
                   bOK_actionPerformed();
         protected void escapeActionPerformed() {
              isOK=false;
              dispose();
         public float getMaxValue() {
              return maxValue;
         public float getMinValue() {
              return minValue;
         public static DecimalFormat formatFactory(String pattern){
              DecimalFormat format = new DecimalFormat(pattern);
              DecimalFormatSymbols dfs = new DecimalFormatSymbols();
              dfs.setDecimalSeparator('.');
              format.setDecimalFormatSymbols(dfs);
              return format;
    }

  • How do I turn off percent symbol in JFormattedTextField

    I am using a custom JFormattedTextField field, that has methods to add masks which apply formatting and add suffix and prefixes.
    It allows the user to see the data in display mode (formatted) or raw (unedited mode)
    Just found a problem though with our display mode when I try and add a suffix of a % symbol after the text.
    It turns out that JFormattedTextField does magic when it sees a %.
    It assumes I want to multiply the data by 100, which I do not. (the data is already stored in terms of percent.)
    I found an ugly hack to solve my problem, which is:
      DecimalFormat displayFormat = new DecimalFormat();
      DecimalFormatSymbols dfs = displayFormat.getDecimalFormatSymbols();
      dfs.setPercent('~'); // set to a symbol we will never use 
      displayFormat.setDecimalFormatSymbols(dfs);
      this.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(displayFormat)));
      // then later we apply our mask
      // used to do this
      // displayFormat.applyPattern(myDisplayFormat);
      // now have to do this so it does not overwrite our percent symbol
      this.displayFormat.applyLocalizedPattern(myDisplayFormat);It seems like there should be an easier way to accomplish this.
    What I was really hoping I could do, is "turn off" the percent substitution functionality.
    i.e. something like displayFormat.disablePercentFormatting(true);
    but at the moment, messing with localised symbols seems like the only way to hack it.
    Anyone have any thoughts? I just want DecimalFormat not to treat a % as a special symbol.
    note:
    Changing the data itself (dividing it by 100) is not an option as the data is entered elsewhere and it would screw up the raw view of the data too.
    Changing the underlying framework (of how we use our display / edit fields and masks etc) is not an option
    as there are hundreds of screens and objects using this framework already with no problems (they dont have a % in their mask though)
    I look forward to bright ideas.
    Cheers,
    - ding

    This behavior is documented in the API of DecimalFormat. If you don't want the special character to be interpreted, you need to quote it:
    Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. They must be quoted, unless noted otherwise, if they are to appear in the prefix or suffix as literals. and
    '      Prefix or suffix      No      Used to quote special characters in a prefix or suffix, for example, "'#'#" formats 123 to "#123". To create a single quote itself, use two in a row: "# o''clock". see also: http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

  • Use JFormattedTextField in 1.3.1

    Hi,
    can someone tell me how, if possible, I can use the JFormattedTextField class in 1.3.1. For an application I am in need of such a component, but it's not acceptible to use a beta version of the jdk for this project.
    or,
    can someone suggest a component with similar functionallity?
    Thanks,
    Frank

    Here is a simple version of JFormattedTextField in 1.3...
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusListener;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import javax.swing.JTextField;
    import javax.swing.text.Document;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
    public class JFormattedField extends JTextField implements ActionListener, FocusListener {
    private NumberFormat format;
    public JFormattedField() {
         this(0.0, 8, new java.text.DecimalFormat("0.00000"));
    public JFormattedField(String value, int columns) {
         this(value, columns, new java.text.DecimalFormat("0.00000"));
    public JFormattedField(String value, int columns, NumberFormat f) {
         this(Double.parseDouble(value), columns, f);
    public JFormattedField(double value, int columns, NumberFormat f) {
    super(columns);
    format = f;
         setHorizontalAlignment(JTextField.RIGHT);
         addActionListener(this);
         addFocusListener(this);
    setValue(value);
    public void focusGained(java.awt.event.FocusEvent f) { }
    public void focusLost(java.awt.event.FocusEvent f) {
         try {
         if (!f.isTemporary())
              setValue(Double.parseDouble(getText()));
         } catch (NumberFormatException ne) {
              Toolkit.getDefaultToolkit().beep();
    public void actionPerformed(ActionEvent a) {
         try {
         setValue(Double.parseDouble(a.getActionCommand()));
         } catch (NumberFormatException ne) {
         Toolkit.getDefaultToolkit().beep();
    public double getValue() {
    double retVal = 0.0;
    try {
    retVal = format.parse(getText()).doubleValue();
    } catch (ParseException e) {
    Toolkit.getDefaultToolkit().beep();
    return retVal;
    public void setValue(double value) {
    setText(format.format(value));
    public void setValue(String value) {
    setText(value);
    protected Document createDefaultModel() {
    return new NumberDocument(format);
    private class NumberDocument extends PlainDocument {
         NumberFormat format;
         NumberDocument(NumberFormat f) {
         this.format = f;
    public void insertString(int offset, String string, AttributeSet as) throws BadLocationException {
         final String NUMBERS = "-.,0123456789";
         try {
              char [] src = string.toCharArray();
              char [] dest = new char[src.length];
              int count=0;
              for (int i=0; i<src.length; i++)
              if (NUMBERS.indexOf(src) != -1)
                   dest[count++] = src[i];
              super.insertString(offset, new String(dest, 0, count), as);
         } catch (Exception e) {
              e.printStackTrace(System.err);
    Sample test program...
    import javax.swing.text.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.awt.*;
    import tools.*;
    public class Field extends JFrame {
    public Field() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(2, 1));
    panel.add(new JFormattedField(0.0,11,new java.text.DecimalFormat("0.00000")));
    panel.add(new JFormattedField(0.0,11,new java.text.DecimalFormat("0.00")));
    panel.add(new JFormattedField("1",11,new java.text.DecimalFormat("0.00")));
    getContentPane().add(panel);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent event) {
    System.exit(0);
    pack();
    public static void main(String[] args) {
    (new Field()).show();
    Hope it helps..
    [email protected]

  • Some questions on JFormattedTextField

    I more or less manage to work with JFormattedTextField, but have not mastered this control fully. I hope that someone can help me with some questions I still have.
    JFormattedTextField field = new JFormattedTextField(); // no-args constructor
    double d = 1.23456; // primitive type will be autoboxed to Double
    field.setValue(d); // AbstractFormatterFactory based on DoubleNow, when the field has the focus, a text value of +1.2+ is displayed. As soon as it looses focus, the text value is changed into +1.235+. I find that weird behaviour and would rather see it the other way around or see the same text in both situations. Can anybody explain me what's happening here? I do not observe this behavior when using one of the other constructors.
    Another problem has to do with internationalization. The Dutch locale, for example, uses a comma as a decimal separator. Users having a scientific background, however, often override the default settings and use a period as a decimal separator (on Windows by changing the regional options). Is there a way of using whatever separator a user has chosen for his system when formatting numbers in Java? I know you can use the DecimalFormatSymbols class to change symbols for a specific locale, but that does not take into account user-specific settings.

    Hi.
    Try this:
    DecimalFormatSymbols fs = new DecimalFormatSymbols();
        fs.setDecimalSeparator('.');
        fs.setGroupingSeparator(',');
    DecimalFormat format = new DecimalFormat("##.#", fs);
    AbstractFormatter formatter    = new NumberFormatter( format );
    AbstractFormatterFactory ff = new DefaultFormatterFactory( formatter, formatter, formatter);
    JFormattedTextField field = new JFormattedTextField();
    field.setFormatterFactory(ff);

  • JFormattedTextField

    Hey!
    I'm having problem with entering numbers after decimal point. I 've set
    two digits after decimal point. when I add first time it's working.
    When try to override it takes third number & rounding it off and adding
    it.
    eg: 38 then overrude 8 with 7 it take 387 and puts 39
    If I enable override mode enable when I entering number reaches cmmma (,) without problem but afterwards it takes next two digits after
    decimal point addes with entered number.
    45.00 inserting 25 then it becomes 452,500.00
    I tried my best to solve it. please someone help me to sort out this
    problem..
    I've added my code here you can test and give me some idea..
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.text.NumberFormatter;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.JTextField;
    import javax.swing.JFormattedTextField;
    import javax.swing.text.DefaultFormatter;
    import java.math.BigDecimal;
    import java.util.Locale;
    import java.text.*;
    import javax.swing.text.MaskFormatter;
    public class NumberCellEditor{
    DecimalFormat numberFormat;
    JFrame frame;
    JFormattedTextField text,text1;
    JPanel panel;
    public void create(){
    text=new JFormattedTextField();
    text1=new JFormattedTextField();
    numberFormat = (DecimalFormat) NumberFormat.getNumberInstance();
    numberFormat.setDecimalSeparatorAlwaysShown(true);
    numberFormat.setMinimumFractionDigits(2);
    NumberFormatter numFormatter = new
    NumberFormatter(numberFormat);
    numFormatter.setAllowsInvalid(false);
    numFormatter.setFormat(numberFormat);
    //numFormatter.setOverwriteMode(true);
    text.setValue(new Float(0.0F));
    text.setFormatterFactory(new
    DefaultFormatterFactory(numFormatter));
    text.setHorizontalAlignment(JTextField.TRAILING);
    public void createComp(){
    frame=new JFrame(" TEST 2");
    panel=new JPanel();
    panel.setLayout(null);
    create();
    text.setBounds(100,100,100,30);
    text1.setBounds(100,200,100,30);
    panel.add(text);
    panel.add(text1);
    frame.getContentPane().add(panel);
    frame.setSize(300,300);
    frame.setVisible(true);
    public static void main (String [] args){
    NumberCellEditor n=new NumberCellEditor();
    n.createComp();
    }

    Hey guys !!!
    Thanks for your advice...
    Do you know why did I post it twice? I want to know the problem is with my code or with some problem in JDK. That's why I've given the full code to run & check...
    Since you guys are well experienced in programming I thought this will a simple problem to solve. well... I'm just started this programming...
    Well.. I think it's not useful to post my problems in to the prestigious JAVA FORUM. Since i'm so young in programming I'll certainly waste your valuable TIME.
    Any way.. Thanks for teaching a lession to me.
    Bye

  • JFormattedTextField.isEditValid() not returning false

    I have the following code, and in the text field you can type all kinds of letters or numbers and it always shows up as having valid input. Why is this? Also, why is the ".01" truncated off when the application starts up? Basically, I want the user to be forced to enter in a floating point number.
    Thank you for your time,
    Brandon Murphy
    import java.awt.Color;
    import java.text.ParseException;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.MaskFormatter;
    public class DocumentListenerAdapter implements DocumentListener
         public DocumentListenerAdapter(JFormattedTextField textField)
              _textField = textField;
         public void changedUpdate(DocumentEvent e) {this.verify();}
         public void insertUpdate(DocumentEvent e) {this.verify();}
         public void removeUpdate(DocumentEvent e) {this.verify();}
         protected void verify()
              if(_textField.isEditValid() == true)
                   _textField.setBorder(null);
              else //(_textField.isEditValid() == false)
                   _textField.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
              System.out.println(_textField.isValid() + ", " +  _textField.getText());
         private JFormattedTextField      _textField      = null;
      public static void main(String argv[])
              JFrame frame = new JFrame("AbstractTextField Test");
             JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
             textField1.getDocument().addDocumentListener(new DocumentListenerAdapter(textField1));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(textField1);
              frame.setVisible(true);
              frame.pack();
    }Edited by: officialhopsof on Jun 16, 2010 2:07 AM

    You never actually set a format on the text field.
    If you turn on setAllowsInvalid the user can actual type "10.blabla" and it'll just accept that as 10, not sure how to fix that.
    import java.awt.Color;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JFormattedTextField.AbstractFormatter;
    import javax.swing.JFormattedTextField.AbstractFormatterFactory;
    import javax.swing.text.InternationalFormatter;
    public class DocumentListenerAdapter {
        public static void main(String args[]) {
            JFrame frame = new JFrame("AbstractTextField Test");
            final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
            textField1.setFormatterFactory(new AbstractFormatterFactory() {
                @Override
                public AbstractFormatter getFormatter(JFormattedTextField tf) {
                    NumberFormat format = DecimalFormat.getInstance();
                    format.setMinimumFractionDigits(2);
                    format.setMaximumFractionDigits(2);
                    InternationalFormatter formatter = new InternationalFormatter(format);
                    formatter.setAllowsInvalid(false);
                    return formatter;
            textField1.addPropertyChangeListener("editValid", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    boolean valid = (Boolean) evt.getNewValue();
                    System.out.println(valid + ", " + textField1.getValue() + ", "
                            + textField1.getText());
                    if (valid) {
                        textField1.setBorder(null);
                    else {
                        textField1.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(textField1);
            frame.setVisible(true);
            frame.pack();
    }

  • Selecting text promatically in a JFormattedTextField

    Greetings!
    I tried to create a FocusListener that selects all the text in a field upon getting focus in a JFormattedTextField. I cannot make it work. Here is what the focusGained method looks like:
    public void focusGained(FocusEvent e) {
    logger.info("Selecting text");
    JFormattedTextField widget = (JFormattedTextField)e.getComponent();
    widget.selectAll();
    I have tried many variants, .select(0,100); .setSelectStart(0); .setSelectionEnd(100); ... etc ...
    My text controls are created in the following manner:
    JFormattedTextField f = new JFormattedTextField(
    new NumberFormatter(new DecimalFormat("#,##0.00")));
    f.setValue(new Double(0.00));
    f.addFocusListener(selectOnFocusListener);
    Thank you for any help.
    Jeremy Cowgar
    [email protected]

    have a look at:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=287089

  • Need help creating a two-digit JFormattedTextField

    I want to create a JFormattedTextField that, while editing, accepts only numbers with two or less digits (i.e. 0 - 99, and blank space), and if the user types anything violating this constraint, the keystroke is ignored. Furthermore, when the text field does not have focus, and the number in it has less than two digits, zero-padding occurs (e.g. 9 -> 09, blank -> 00). Furthermore, would it be possible enforce the same behavior when calling setText() on the text field? Any help would be appreciated.

    I've read it (many times), but both MaskFormatter and DecimalFormat don't solve my problem completely. MaskFormatter doesn't handle padding numbers with zero, and DecimalFormat doesn't constrain the input while user is editing. I've also tried using AbstractFormatterFactory to combine MaskFormatter and DecimalFormatter for the editing and displaying behavior, but can't get it to work correctly. I'm wondering if there's a simple solution I'm missing.

  • Need help with JFormattedTextField and DocumentListener

    I can't get my JTextField to work with my DocumentListener. I'm very new to Java so the solution might be quite simple. Any help is very appreciated!
    Here is my complete code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.JFormattedTextField.AbstractFormatter;
    import java.text.*;
    public class Test extends JFrame {
    private JFormattedTextField eingabeFeld;
    private JFormattedTextField ausgabeFeld;
    private String eingabe;
    private String ausgabe;
    public Test() {
         super("DocumentListener-Test");
         NumberFormatter textFormatter = new NumberFormatter(new DecimalFormat("###,##0.0#"));
         textFormatter.setCommitsOnValidEdit(true);
         textFormatter.setAllowsInvalid(false);
         DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(textFormatter);
         EingabeListener eingabeListener = new EingabeListener();
         JFormattedTextField eingabeFeld = new JFormattedTextField();
         eingabeFeld.getDocument().addDocumentListener(eingabeListener);
         eingabeFeld.getDocument().putProperty("name", "EingabeFeld");
         eingabeFeld.setFormatterFactory(fmtFactory);
         AbstractFormatter formatter = eingabeFeld.getFormatter();
         JFormattedTextField ausgabeFeld = new JFormattedTextField();
         ausgabeFeld.setEditable(false);
         // this is not needed!
         //ausgabeFeld.getDocument().addDocumentListener(eingabeListener);
         //ausgabeFeld.getDocument().putProperty("name", "AusgabeFeld");
         //ausgabeFeld.setText("1");
         JPanel contentPane = new JPanel();
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
         contentPane.setLayout(gridbag);
         c.gridx = 0;
         c.gridy = 0;
         c.ipadx = 200;
         gridbag.setConstraints(eingabeFeld, c);
         contentPane.add(eingabeFeld);
         c.gridx = 0;
         c.gridy = 1;
         c.ipadx = 200;
         gridbag.setConstraints(ausgabeFeld, c);
         contentPane.add(ausgabeFeld);
         setContentPane(contentPane);
    class EingabeListener implements DocumentListener {
         public void insertUpdate(DocumentEvent e) {
              Calculate(e);
         public void removeUpdate(DocumentEvent e) {
              Calculate(e);
         public void changedUpdate(DocumentEvent e) {
         private void Calculate(DocumentEvent e) {
              // this does not work!
              //eingabe = eingabeFeld.getText();
              //double wert = Double.parseDouble(eingabe);
              //wert = wert/2;
              //ausgabe = Double.toString(wert);
              //ausgabeFeld.setText(eingabe);
    public static void main(String[] args) {
         final Test frame = new Test();
         frame.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   System.exit(0);
         frame.pack();
         frame.setVisible(true);
    }

    Thanks that worked! Now I changed
    JFormattedTextField ausgabeFeld = new JFormattedTextField(); to
    ausgabeFeld = new JFormattedTextField(); as well.
    I changed eingabe, ausgabe from String to Object and .getText and .setText into .getValue and .setValue. I also added ausgabeFeld.setFormatterFactory(fmtFactory);
    AbstractFormatter formatteraus = ausgabeFeld.getFormatter();
    But now I have the probelm, that I don't know how to parse the eingabe Object into a double and back to be able to calculate with it.
    And another problem is, that the ausgabeFeld get's only updated and the eingabeFeld formatted if the eingabeFeld loses focus.
    I hope anybody can help me with these problems now! Thanks in advance.

  • Serious: FormattedTextField with DecimalFormat

    I have a strange behaviour of a formattedTextField.
    I studied all the available materials that I have found but I didn't find an answer.
    I have a formattedTextField with a defaultFormatter based on the DecimalFormat constructed for US Locale:
    Locale loc = Locale.US;
    JFormattedTextField fTextField = new JFormattedTextField (new Double("0"));
    fTextField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    DecimalFormatSymbols decimalFormatSymbols=new DecimalFormatSymbols(loc);
    char decSep=decimalFormatSymbols.getDecimalSeparator();
    char grpSep=decimalFormatSymbols.getGroupingSeparator();
    char dig = decimalFormatSymbols.getDigit();
    char zeroDigit = decimalFormatSymbols.getZeroDigit();   After this I created the patern for the DecimalFormat:
    String pat = ""+dig+grpSep+dig+dig+zeroDigit+decSep+zeroDigit+zeroDigit+zeroDigit+zeroDigit;//"#,##0.0000"
    System.out.println("The patern is:"+pat+"!");This creates the patern "#,##0.0000". After this I created the formatter fmt based on this patern and the DecimalFormatSymbols for US Locale.
    DecimalFormat decimalFormat = new DecimalFormat(pat, decimalFormatSymbols);
    DefaultFormatter fmt = new NumberFormatter(decimalFormat);
    fmt.setAllowsInvalid(false);
    fmt.setCommitsOnValidEdit(false);
    fmt.setOverwriteMode(true);After this, I create the DefaultFormatterFactory for my fTextField based on this fmt Formatter.
    DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(fmt);
    fTextField.setFormatterFactory(fmtFactory); Now I can initialize my fTextField:
    AbstractFormatter formatter = fTextField.getFormatter();
    if (formatter != null) {
    String text = "0.1";
    try {
    Double j =(Double)formatter.stringToValue(text);
    fTextField.setValue(j);
    } catch (ParseException pe) {System.out.println("Exception when the initial value is parsed");}} The initial value is 0.1 that will be displayed as 0.1000 according to the patern that is created to have 4 decimals initialized with 0 and 1 or more integers separated (in groups of 3) by the group separator.
    All is ok. When I type something in the field, the character fromm the right of the cursor is replaced as I wish. This is ok. The problem is that when the cursor is in the left part of the decimal separator and I type something (a number), then the 4 decimals are considered integers and they are passed in the left position of the decimal separator and the decimal part is initialized with 0000 (the default value according to the patern).
    For example:
    When I have 1,234|,5678 ('|' means the cursor) and I press 9 the new value displayed will be: 123,495,678.0000
    What is the problem?
    Maybe I don't use the correct patern, or it is a bug!
    Please HELP. I have studied very strongly FormattedTextField and I answered to a lot of problems of this type on the forum hopping that I will find something similar. Maybe somebody can help me!
    Thank you!

    For what it's worth I've had lots of problems with DecimalFormat and I've come to the conclusion it's unusably broken.
    I've done most of my tests using a pattern of "#,##0.00;-#,##0.00".
    1) The getMaximumIntegerDigits() is around 300, not 4 (so I set it to 4).
    2) Entering a '-' before any digits is ignored.
    3) Entering '-' after some digits mis-places the carat by 1 place.
    4) Entering "12345" results in "2,345|.00" being displayed.
    5) Pressing ERASE at this point displays "4500|.00"
    6) Moving to "4,5|00.00" and pressing 8 results in "5,80|0.00"
    7) Entering a third decimal digit causes rounding to be applied each and every time a digit is typed.
    8) getValue() returns null until TWO digits are entered.
    There's probably more...
    For what it's worth, here's my test-code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;
    /** A Formated Text Field that uses a NumberFormatter
    public class FieldNumber extends JFormattedTextField
    NumberFormatter iNumberFormatter = new NumberFormatter();
    DecimalFormat iDecimalFormat = (DecimalFormat)NumberFormat.getNumberInstance();
    String iPattern = null;
    /** An empty field
    public FieldNumber()
    {   jbInit();
    private void jbInit()
    {   setFormatterFactory(new DefaultFormatterFactory(iNumberFormatter));
    iNumberFormatter.setFormat(iDecimalFormat);
    iNumberFormatter.setAllowsInvalid(false);
    iNumberFormatter.setCommitsOnValidEdit(true);
    this.setHorizontalAlignment(JTextField.RIGHT);
    /** Sets the Format Pattern
    public void setPattern(String aPattern)
    {   iPattern = aPattern;
    iDecimalFormat.applyPattern(aPattern);
    iDecimalFormat.setMaximumIntegerDigits(countDigits(aPattern));
    int countDigits(String aPattern)
    {   int lDigits = 0;
    for (int i = 0; i < aPattern.length(); i++)
    {   char ch = aPattern.charAt(i);
    if ( (ch == '#')
    || (ch == '0'))
    {   lDigits += 1;
    else if ( (ch == '.')
    || (ch == ';'))
    {   break;
    return lDigits;
    /** Gets the Format Pattern
    public String getPattern()
    {   return iPattern;
    public static void main(String[] args)
    {   JFrame frame = new JFrame();
    FieldNumber fieldNumber = new FieldNumber();
    fieldNumber.setPattern("#,##0.00;-#,##0.00");
    frame.addWindowListener(new WindowAdapter()
    { public void windowClosing(WindowEvent event)
    { System.exit(0);
    frame.getContentPane().add(fieldNumber);
    frame.pack();
    frame.setVisible(true);

  • JFormattedTextField with setDefaultButton

    Hello all,
    I seem to be having some trouble with getting the desired behavior out of JFormattedTextField when combined with setDefault button. The text field commits after every keystroke (to maintain correct formatting) and when I'm editing I have to hit Enter twice to activate the default button, once presumably to force the commit, and a second time to activate the default button. Is there a way to get the JFormattedTextField to not consume the first Enter so it activates the default button?
    Here's a small sample that shows the undesired behavior (JDK 1.5.0_05)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.NumberFormatter;
    import java.text.DecimalFormat;
    public class TestDefaultButton {
        private static void createAndShowGui() {
         final JFrame frame = new JFrame("Test Default Button");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            NumberFormatter idFormatter = new NumberFormatter(
                    new DecimalFormat("##,###,###"));
            idFormatter.setAllowsInvalid(false);
            idFormatter.setMaximum(99999999);
            JFormattedTextField text = new JFormattedTextField(idFormatter);
            text.setColumns(10);
         JButton button = new JButton("Press me!");
         button.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  JOptionPane.showMessageDialog(frame, "Click!", "",
                                    JOptionPane.INFORMATION_MESSAGE);
         JPanel panel = new JPanel();
         panel.add(text);
         panel.add(button);
         frame.getContentPane().add(panel);
         frame.getRootPane().setDefaultButton(button);
         frame.pack();
         frame.setVisible(true);
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                  createAndShowGui();
    }If I make the formatted text field a normal text field, everything works as expected, so this is why I guess there must be some different interaction with the formatted text field.
    I'd appreciate any hints on how to resolve this.
    Thanks and regards,
    J. Bromley

    This occurs because the formattted text field binds Enter to an Action, whereas
    the regular text field does not. You can remove this binding in the example code
    with the following change:
              text.setColumns( 10 );
              for ( ActionMap map = text.getActionMap(); map != null; map = map.getParent() )
                   map.remove( "notify-field-accept" );In this example, it doesn't seem to have any other effects, but in a real program,
    losing the commit on enter may be problematic.

Maybe you are looking for

  • Windows Wont Recognize

    I'm updating my Dads iPod for him and for the first time ever, Windows/iTunes wont recognize it. On the iPods display screen it says do not dissconnect so its not my USB ports nor the cable. Any ideas? BTW, this is the iPod Color U2 version thing

  • Drag and Drop in CSS Styles Panel

    So, I am going through Dreamweaver CS5 Classroom in a Book. In lesson 6, pages 106 through109, it tells you to drag and drop rules in the CSS Styles Panel into a certain order.  I can't seem to get it to work for me.  Am I missing something?

  • How do know that the battery is fully charged on ios 7

    How do know that the battery is fully charged on ios 7

  • Edit Process order locked in ECC

    Hi Experts, I am saving process order from APO - /sapapo/rrp3 and the same proc order should ideally be updated in ECC - COR3 transaction. This happens correctly when 'LOCKED BY WORKFLOW' status is initial in COR3. And doesn't get updated in ecc when

  • Java.io.IOException: Service TxXMLFileDescriptorsStore at C:\product\10.1.3

    Hi, When I try to register a ESB process, this gives me an error like summary: An unhandled exception has been thrown in the ESB system. The exception reported is: "java.io.IOException: Service TxXMLFileDescriptorsStore at C:\product\10.1.3.1\OracleA