8 Replies Latest reply: Sep 26, 2012 3:25 AM by mrsAngelo RSS

    assign number formatting to a JFormattedTextField in dynamic mode

    843807
      hi

      I need to assign number formatting to a JFormattedTextField
      (to define decimal digit and localization for the currency).

      I was able to solve this problem if I assign formatting when the JFormattedTextFieldis created:
      import java.awt.FlowLayout;
      import java.awt.event.ActionEvent;
      import java.text.NumberFormat;
      import java.util.Locale;
      import javax.swing.JButton;
      import javax.swing.JFormattedTextField;
      import javax.swing.JFrame;
      import javax.swing.JLabel;
      import javax.swing.JOptionPane;
      import javax.swing.text.DefaultFormatterFactory;
      import java.awt.event.ActionListener;
      import javax.swing.JOptionPane;
      import javax.swing.JFormattedTextField.AbstractFormatterFactory;
      import javax.swing.text.NumberFormatter;
      
      /**
       *
       *
       */
      public classTestTheNumFormatProblem {
          
          /** Creates a new instance of testTheNumFormatProblem */
          public TestTheNumFormatProblem() {
          }
          
          public static void main(String args[]) {
              Finestra finestra = new Finestra();
          }
      }  // class testTheNumFormatProblem
      
      class Finestra extends JFrame{
          JLabel jl;
          JFormattedTextField jft ;
          JButton jb = new JButton("but");
          public Finestra(){
              setLayout(new FlowLayout());
              jl = new JLabel("Try with formatted text field   ");
              jft = setFormat(jft);
              add(jb);
              //
              add(jl);
              add(jft);
              jft.setColumns(10);
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
              setSize(400,300);
              setVisible(true);
              jb.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                      JOptionPane.showMessageDialog(jb, "nel text Box : " + jft.getText());
                  }
              });
          }
          
          private JFormattedTextField setFormat(JFormattedTextField jft ){
              DefaultFormatterFactory aff ;
              NumberFormat numberFormat;
      //        Locale local = new Locale("it", "IT");
              Locale local = new Locale("en", "US");
              
              numberFormat = NumberFormat.getCurrencyInstance(local);
              numberFormat.setMinimumFractionDigits(3);
              jft = new JFormattedTextField(numberFormat);
              jft.setValue(new Double(342.796));
              return jft;
          }
      }
      *But I have to assign formatting after the JFormattedTextField is already created... *
      (using some method like jFormattedTextField.setFormatterFactory(... )

      In this case i am not able to do the program work good..

      Any help or explanation to assign formatting in dynamic way is welcome

      thank you

      regards

      tonyMrsangelo
        • 1. Re: assign number formatting to a JFormattedTextField in dynamic mode
          843807
          hii,

          is this siutable for you --->
          import java.awt.BorderLayout;
          import java.awt.Dimension;
          import java.awt.event.ActionEvent;
          
          import java.math.RoundingMode;
          import java.text.NumberFormat;
          import java.util.Locale;
          import javax.swing.*;
          
          public class TextTest {
          
              JLabel jl;
              JFormattedTextField jft, jft1, jft2, jft3, jft4;
              JButton jb = new JButton("but");
          
              public TextTest() {
                  JFrame frame = new JFrame("Text Test");
                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  jl = new JLabel("Try with formatted text field   ");
                  Locale local1 = new Locale("en", "US");
                  int minFra = 0;
                  int maxFra = 3;
                  jft = setFormat(jft, local1, minFra, maxFra);
                  //jft.setColumns(20);
                  jft.setMaximumSize(new Dimension(100, 20));
                  jft.setMinimumSize(new Dimension(100, 20));
                  jft.setPreferredSize(new Dimension(100, 20));
                  local1 = new Locale("gb", "GB");
                  minFra = 0;
                  maxFra = 2;
                  jft1 = setFormat(jft1, local1, minFra, maxFra);
                  //jft1.setColumns(20);
                  jft1.setMaximumSize(new Dimension(100, 20));
                  jft1.setMinimumSize(new Dimension(100, 20));
                  jft1.setPreferredSize(new Dimension(100, 20));
                  local1 = new Locale("de", "DE");
                  minFra = 0;
                  maxFra = 3;
                  jft2 = setFormat(jft2, local1, minFra, maxFra);
                  //jft2.setColumns(20);
                  jft2.setMaximumSize(new Dimension(100, 20));
                  jft2.setMinimumSize(new Dimension(100, 20));
                  jft2.setPreferredSize(new Dimension(100, 20));
                  local1 = new Locale("jp", "JP");
                  minFra = 0;
                  maxFra = 0;
                  jft3 = setFormat(jft3, local1, minFra, maxFra);
                  //jft3.setColumns(20);
                  jft3.setMaximumSize(new Dimension(100, 20));
                  jft3.setMinimumSize(new Dimension(100, 20));
                  jft3.setPreferredSize(new Dimension(100, 20));
                  local1 = new Locale("hk", "HK");
                  minFra = 0;
                  maxFra = 3;
                  jft4 = setFormat(jft4, local1, minFra, maxFra);
                  //jft4.setColumns(20);
                  jft4.setMaximumSize(new Dimension(100, 20));
                  jft4.setMinimumSize(new Dimension(100, 20));
                  jft4.setPreferredSize(new Dimension(100, 20));
                  frame.add(jb);
                  //
                  frame.add(jl);
                  frame.add(jft, BorderLayout.NORTH);
                  frame.add(jft1, BorderLayout.SOUTH);
                  frame.add(jft2, BorderLayout.WEST);
                  frame.add(jft3, BorderLayout.EAST);
                  frame.add(jft4, BorderLayout.CENTER);
                  jb.addActionListener(new java.awt.event.ActionListener() {
          
                      public void actionPerformed(ActionEvent e) {
                          JOptionPane.showMessageDialog(jb, "nel text Box : " + jft.getText());
                      }
                  });
          
                  frame.setSize(new Dimension(600, 100));
                  frame.setVisible(true);
              }
          
              public static void main(String[] args) {
                  new TextTest();
              }
          
              private JFormattedTextField setFormat(JFormattedTextField jft, Locale local1, int minFra, int maxFra) {
                  NumberFormat numberFormat;
                  Locale local = local1;
                  int setMin = minFra;
                  int setMax = maxFra;
                  numberFormat = NumberFormat.getCurrencyInstance(local);
                  numberFormat.setMinimumFractionDigits(setMin);
                  numberFormat.setMaximumFractionDigits(setMax);
                  numberFormat.setRoundingMode(RoundingMode.HALF_UP);
                  jft = new JFormattedTextField(numberFormat);
                  jft.setValue(new Double(342.796));
                  return jft;
              }
          }
          
          ... kopik
          • 2. Re: assign number formatting to a JFormattedTextField in dynamic mode
            843807
            hi kopik,


            thank you for answering me...
            I read your code.. but it works in the same way that I already posted.

            I need a different solution:
            I am looking for a possibility to assign a "number format" to JFormatTextField components not by the constructor, but by a method like jFormattedTextField.setFormatterFactory(... ).

            . . . . . . . . .
            This because the code that I am writing is part of a library where the JFormatTextFiend is already instantiated (it come how a parameter)
            and there I need to set a "number format" that every time can change, depending from the conditions the program is executed...

            regards

            tonyMrsangelo
            • 3. Re: assign number formatting to a JFormattedTextField in dynamic mode
              843807
              hii,

              in that I can help you with jFormattedTextField.setFormatterFactory(... )

              I do not know what you're doing, but if you want ot play with Ccy(s), the syntax for finance is:
              1/ my side (buy or sell, B&S or S&B, lend or borrow) / String
              +
              2/ currency (ccy pair) ---> Ccy shortName (USD/EUR/GBP/JPY ...)/ String
              +
              3/ amount (nominal) ---> excluding JPY are quoted on 2dec. places (quoted ccy) / Double "in some creations Float"
              +
              4/ rate (price, price in pct) ---> floating No.dec places / Double "in some creations Float"
              +
              date(s) condicion(s) / Date (shortFormat dd/mm/yyyy or mm/dd/yyyy) <--- basicaly/usually hardcoded syntax

              nowhere is the Locale for currency and amount, if your solutions isn't to do with finance, then ingnore that's

              ... kopik
              • 4. Re: assign number formatting to a JFormattedTextField in dynamic mode
                Jörg
                Hello Tony,

                when JFormattedTextField was released in 1.4(?) I was full of joyous
                expectations, but soon got rather frustrated, for I never mastered this class or
                at least was not satisfied with its behaviour. To this adds my attempt below to
                change a formatter at runtime by means of the install method. The code is in no
                way satisfying; e.g. the fraction part is not returned. I post the code only
                to show what is NOT working either.

                If it is acceptable to you, you might create n JFormattedTextFields each one
                having its specific formatter, and all placed at the same location on the screen
                but only one is visible at a time. Sounds awkward, I admit.
                I personally ended up in writing my own JTextField with a DocumentFilter which
                allows control at every keystroke of the user.
                import java.awt.*;
                import java.awt.event.*;
                import java.text.*;
                import java.util.*;
                import javax.swing.*;
                import javax.swing.text.*;
                
                public class ChangingFormatter extends JFrame implements ActionListener {
                  int icurrentFormatter;
                  JFormattedTextField tf;
                  JRadioButton rbEnglish, rbFrench, rbFloat, rbInteger;
                  JLabel lb;
                  NumberFormatter nfEn, nfFr, nfFlo, nfInt;
                  final int ENGLISH=1, FRENCH=2, FLOAT=3, INTEGER=4;
                
                  public ChangingFormatter() {
                    setSize(300, 200);
                    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                    JPanel pWest= new JPanel(new GridLayout(4,1));
                    add(pWest, BorderLayout.WEST);
                    rbEnglish= new JRadioButton("English currency", true);
                    rbEnglish.addActionListener(this);
                    pWest.add(rbEnglish);
                    rbFrench= new JRadioButton("French currency");
                    rbFrench.addActionListener(this);
                    pWest.add(rbFrench);
                    rbFloat= new JRadioButton("Float");
                    rbFloat.addActionListener(this);
                    pWest.add(rbFloat);
                    rbInteger= new JRadioButton("Integer");
                    rbInteger.addActionListener(this);
                    pWest.add(rbInteger);
                    ButtonGroup bg= new ButtonGroup();
                    bg.add(rbEnglish);
                    bg.add(rbFrench);
                    bg.add(rbFloat);
                    bg.add(rbInteger);
                    JPanel pCenter= new JPanel(null);
                    add(pCenter, BorderLayout.CENTER);
                    tf = new JFormattedTextField();
                    tf.setBounds(70,30, 100,20);
                    tf.addActionListener(this);
                    pCenter.add(tf);
                    lb= new JLabel();
                    lb.setBounds(70,80, 100,20);
                    pCenter.add(lb);
                
                    NumberFormat fmt= NumberFormat.getCurrencyInstance(new Locale("en", "GB"));
                    fmt.setMaximumIntegerDigits(3);
                    fmt.setMaximumFractionDigits(2);
                    fmt.setMinimumFractionDigits(2);
                    nfEn= new NumberFormatter(fmt);
                //    nfEn.setAllowsInvalid(false);
                    nfEn.setValueClass(Double.class);
                
                    fmt= NumberFormat.getCurrencyInstance();
                    fmt.setCurrency(Currency.getInstance("EUR"));
                    fmt.setMaximumIntegerDigits(3);
                    fmt.setMaximumFractionDigits(2);
                    fmt.setMinimumFractionDigits(2);
                    nfFr= new NumberFormatter(fmt);
                    nfFr.setAllowsInvalid(false);
                    nfFr.setValueClass(Double.class);
                
                    fmt= NumberFormat.getInstance();
                    fmt.setMaximumIntegerDigits(3);
                    fmt.setMaximumFractionDigits(2);
                    fmt.setMinimumFractionDigits(2);
                    nfFlo= new NumberFormatter(fmt);
                    nfFlo.setAllowsInvalid(false);
                    nfFlo.setValueClass(Double.class);
                
                    fmt= NumberFormat.getIntegerInstance();
                    fmt.setMaximumIntegerDigits(6);
                    nfInt= new NumberFormatter(fmt);
                    nfInt.setAllowsInvalid(false); // does not work
                    nfInt.setValueClass(Integer.class);
                
                //  English is initially on, so install the formatter
                    tf.setValue(0);
                    nfEn.install(tf);
                    icurrentFormatter= ENGLISH;
                    setVisible(true);
                    tf.requestFocusInWindow();
                  }
                
                  public static void main(String args[]) {
                    EventQueue.invokeLater(new Runnable() {
                      public void run() {
                     new ChangingFormatter();
                      }
                    });
                  }
                
                
                  public void actionPerformed(ActionEvent evt) {
                    Object o= evt.getSource();
                    if (o==tf) {
                      System.out.println(tf.getText());
                      System.out.println(tf.getValue());
                      System.out.println("");
                      lb.setText(""+tf.getValue());
                      tf.setValue(0);
                      tf.requestFocusInWindow();
                      return;
                    }
                    if (icurrentFormatter==ENGLISH)
                //      nfEn.install(null);
                      nfEn.uninstall();
                    else if (icurrentFormatter==FRENCH)
                      nfFr.uninstall();
                    else if (icurrentFormatter==FLOAT)
                      nfFlo.uninstall();
                    else
                      nfInt.uninstall();
                    if (rbEnglish.isSelected()) {
                      nfEn.install(tf);
                      icurrentFormatter= ENGLISH;
                    }
                    else if (rbFrench.isSelected()) {
                      nfFr.install(tf);
                      icurrentFormatter= FRENCH;
                    }
                    else if (rbFloat.isSelected()) {
                      nfFlo.install(tf);
                      icurrentFormatter= FLOAT;
                    }
                    else {
                      nfInt.install(tf);
                      icurrentFormatter= INTEGER;
                    }
                    lb.setText("");
                    tf.setValue(0);
                    tf.requestFocusInWindow();
                  }
                }
                • 5. Re: assign number formatting to a JFormattedTextField in dynamic mode
                  843807
                  Hi Joerg,

                  thank you for your kind answer.

                  I can't follow your suggestion to solve my problem, but I am happy to know I am not alone to have trouble with
                  formatting number...

                  Thank you for the time you spent to answer me...

                  I am looking for write some code good for set formatting numbers in JFormatTextField at run time.

                  If I'll find some good solution I post it here..

                  still thank you

                  regards
                  tonyMrsangelo.
                  • 6. Re: assign number formatting to a JFormattedTextField in dynamic mode
                    mrsAngelo
                    Hi,

                    I wont to close this thread giving the code to solve this problem ..
                    public class LocalizeCurrencyInFormattedTextField extends JFrame {
                    
                        JFormattedTextField txtFld;
                    
                        public LocalizeCurrencyInFormattedTextField() { // constructor
                            txtFld = new JFormattedTextField();
                            txtFld.setColumns(8);
                            this.add(txtFld);
                             //       
                            Locale locale = new Locale("en", "US");
                    //        locale = Locale.ITALY;    
                            NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
                            NumberFormatter numberFormatter = new NumberFormatter(numberFormat);
                            DefaultFormatterFactory defaultFormatterFactory = new
                                                                          DefaultFormatterFactory(numberFormatter);
                            txtFld.setFormatterFactory(defaultFormatterFactory);
                            txtFld.setValue(new Double(3.9));
                        } // constructor
                    
                        public static void main(String[] args) {
                            LocalizeCurrencyInFormattedTextField cc = new LocalizeCurrencyInFormattedTextField();
                            cc.setVisible(true);
                            cc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            cc.setSize(200, 150);
                            cc.setLocation(100, 100);
                            cc.setVisible(true);
                        } // main()
                    } // class LocalizeCurrencyInFormattedTextField
                    • 7. Re: assign number formatting to a JFormattedTextField in dynamic mode
                      Jörg
                      A solution after almost three years. That's what I call a tough researcher. Thank you Tony and keep on trucking.
                      • 8. Re: assign number formatting to a JFormattedTextField in dynamic mode
                        mrsAngelo
                        Hi jorg,

                        I found the solution before then tree years after than I had the problem... :-)
                        Only I forgot to give mine possible solution to it.

                        Now I found for chance this thread and I would like close the question to benefit the others..

                        Thank you: when I pose the question you direct me in the right way .

                        Regards