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

Similar Messages

  • How to see a null or empty value in JFormattedTextField

    Hello, I am having a problem. I'm trying to use a JFormattedTextField, and I keep getting errors.
    I know what is causing the error, but I don't know how to fix it.
    Here is my code:
    String cf = countFTX.getText();
    if(cf.equals(" ")) {
      i = Integer.valueOf(countJTX.getText());
    }else{ i = Integer.valueOf(countFTX.getText()); }what happens is I get an error when it goes to change it into an int. Because it see's it as being (" ") and not (" ") or even ("") so it doesn't fit into my if statement. And returns it being false, then tries to turn it into an int, and blows up there.
    Now how can I fix my if statement to be able to see if nothing was entered, and if so then use the countJTX and not the countFTX?
    countJTX is a regular JTextField, and countFTX is a JFormattedTextField.
    the JTX is filled automaticaly with an int, and if there needs to be a change, the user puts it into the FTX. (so you understand the logic behind it)
    any ideas? or should i just revert to not using the FTX?

    you need to know the differenct between NULL and "" (empty) of a string. Also both of these values cann't converted to in integer so you can not call Integer.valueOf(cf). I don't understand why you need to do that. Instead:
        String cf = countFTX.getText();
        if(cf == null || cf.length() == 0)) {
            i = ?; //something you want i to be when cf is null or empty but not call Integer.valueOf(countJTX.getText());
        }else{
            i = Integer.valueOf(cf);
        }Also, you may need to add try/catch exceptions.

  • 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);
              }

  • How to use multiple formats in one JFormattedTextField

    Hi,
    I am looking for a way to allow multiple formats in the same JFormattedTextField. Let's say I want to allow input like:
    a) 123-AB-123
    and
    b) AB-12345-CD
    Of course I could use an InputVerifier of my own combined with regular expressions to see if the input matches. But I like the way JFormattedTextField supports the UserInput by displaying a Placeholder String. So the User sees what the input might look like.
    I'd tried to write a FormatterFactory of my own, which will return either a MaskFormatter for a) or b) but the JFormattedTextField checks out the Formatter only when gaining or loosing focus. What should happen is that it checks out the formatter after each keystroke.
    Does anyone know a solution for this or how I could force the FormattedTextField to REget it's formatter?
    Thanks
    Thimo

    Check out the following; it provides code for a regular expression formatter:
    http://java.sun.com/products/jfc/tsc/articles/reftf/
    Unfortunately, this does not support the 'placeholder' notion like the MaskFormatter does, if that's what you were talking about. I'm not sure how you could cobble them together, since with the MaskFormatter you don't have to type the mask literal characters, but you would need to with the regular expression.
    : jay

  • 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 can I set this text in a JformattedTextField ?

    Hi,
    I have a JFormattedTextField with this mask "#####-###"
    When I'm typing It works very fine, but when I call the setText( "12345") It doesn't work, it clears the field.
    If I call setText( "12345-123" ) It work very fine.
    when I don't have all the numbers in the setText() it clears the field.
    Is it a bug ?
    Can someone help me ?
    Thanks.
    wmiro.

    hi,
    the problem is that I'm using this mask "#####-###" to enter the Brazil postal code, we have some cities which every street has a postal code like this:
    A st, postal code 03986-150
    B st, postal code 03986-250
    but we have some other smaller cities which doesn't have a different postal code each street, like this:
    A neighborhood, postal code 05089
    B neighborhood, postal code 05090
    the the user will type only five numbers, the system will accept, but when the user needs to see the information he can't because the setText() fail.
    I've been thinking I must complete with zeros or change the mask to "00000-000".
    Is that the best way to solve this problem ?
    thanks
    wmiro.

  • 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

  • Info on JFormattedTextField

    Which is the best way to transfer from JFormattedTextField to database. The conventional way of getting Text and inserting into database or Is there any other way where u can connect to database field directly like in VB or any other packages.
    Also based on events like LostFocus of InFocus of JFormattedTextField, I need to write different codes. Where do I get such examples.?

    Strange, until today I do not remember ever hearing about this view before today and now I see two requests for information about this view.
    All I know is that the 11g Reference manual entry for my downloaded version it is devoid of information and does not even show the column datatypes. I had no luck looking on the online docs either.
    Now I am curious.
    Just tagging along to see if anyone knows anything.
    Apparently this undocumented view is related to the AWR.
    -- Mark D Powell --

  • 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]

  • JFormattedTextField - verfiier problem

    I have a problem using JFormattedTextField for data entry,
    (see _postcodeTextField below ).
    Specifiying a MaskFormatter does restirct the data accepted, in this case to 4 numbers.
    My problem lies with the InputVerifier.
    When I shift the focus (using the <TAB> key) the verifier is invoked. If the
    input is invalid (e.g. 356 which consists of 3 numbers not 4) then as expected
    there is a Beep and a message dialog appears.
    Once the dialog is closed, the focus returns to the _postcodeTextField as expected.
    However, if I then enter a number, it does not appear, but if I enter the number again,
    it appears.
    Why is the first number lost?
    This code has been derived from examples found on the Sun site.
    Curiously there is mention of "focus-transfer problems" with the verifier.
    I like the ability to define an input mask to restirct data entry, but I am
    disappointed by the problems I have encountered in verification.
    I have tried a FocusHandler (extends FocusAdapter) but this also has problems.
    The new JFormattedTextField looks capable of providing the functionality I require,
    but it appears to have its quirks and will need a patch in time.
    Meanwhile, any suggestions?
    _postcodeTextField = getTextFieldWithFormat("####");
    _postcodeTextField.setToolTipText("4 digit code e.g. 4065");
    private JFormattedTextField getTextFieldWithFormat( String format )
    MaskFormatter formatter = null;
    try
    formatter = new MaskFormatter(format);
    catch (java.text.ParseException exc)
    System.err.println("formatter is bad: " + exc.getMessage());
    JFormattedTextField ftf = new JFormattedTextField(formatter);          
    ftf.setFont( new Font( "Arial", Font.PLAIN, 14 ) );
    ftf.setColumns(format.length());      
    ftf.setInputVerifier(new FormattedTextFieldVerifier());
    return ftf;     
    } // getTextFieldWithFormat()
    public class FormattedTextFieldVerifier extends InputVerifier
    public class FormattedTextFieldVerifier extends InputVerifier
    public boolean verify(JComponent input)
    if (input instanceof JFormattedTextField)
    JFormattedTextField ftf = (JFormattedTextField) input;
    try
    ftf.commitEdit();
    catch (ParseException pe )
    return false;
    return true;               
    } // verify()          
    public boolean shouldYieldFocus(JComponent input)
    boolean inputOK = verify(input);
    if (!inputOK)
    //Avoid possible focus-transfer problems when bringing up
    //the dialog by temporarily removing the input verifier.
    //This is a workaround for bug #4532517.
    input.setInputVerifier(null);
    Toolkit.getDefaultToolkit().beep();
    //Display a warning message.
    String message = "Please try again.";
    JOptionPane.showMessageDialog(null, message,
    "Invalid Value", JOptionPane.WARNING_MESSAGE);
    //Reinstall the input verifier.
    input.setInputVerifier(this);
    return inputOK;
    } // shouldYieldFocus()
    } // FormattedTextFieldVerifier class

    (this could be a duplicate post
    first reply disappeared into the ether)
    Meanwhile I consider you have earnt the 10 Duke points I attached to the\is topic.
    I imagine I have to award them to you or something? How do I do that?I don't really know, but keep them for when someone spends a fair bit of
    time and effort solving a problem for you.
    In this case it was just a matter of testing the code and reporting the result.
    Thanks for the offer.

  • Problem with JFormattedTextField

    Hi,
    I Want to set Max length of text in JFormattedTextField..
    I've tried to extend PlainDocument and override insertString and updateString, but it doesn't work.
    How can do it.
    Thanks.

    I've solved the problem with a subclass of DocumentFilter.
    Overriding the following methods : insertString,remove and update

  • 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.

  • Big problem with JFormattedTextField.

    When I use a JFormattedTextField to receive on input just letters when the JFormattedTextField loses focus it just clear the field! Why that?
    try  {
             MaskFormatter mask = new MaskFormatter("????????????????????");
             mask.setValidCharacters("abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ");
             nameText = new JFormattedTextField(mask);
       catch(ParseException pe) {
       }When the JTextFormattedTextField loses the focus it gets empty. Why?
    And I have another important question: Besides letters, I need to receive empty spaces on my JFormattetTextField. How can I set this on setValidCharacters method?
    Thanks!

    You should be displaying a message when you handle an Exception.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • More problem with JFormattedTextField

    Here is the code where I want size and input validation for JFormattedTextField
    MaskFormatter f10=new MaskFormatter("***************");
    f10.setValidCharacters("0123456789");
    t4= new JFormattedTextField(f10);
    It's behaving in funny way. It allows me only specfied no of characters(15 here) and only nos. But after entering nos and when it changes the focus, the entered data is disappearing. What could be the problem?

    Interesting Problem,
    Watching for result.

  • Functionality of JFormattedTextField and JComboBox in one control

    Hi,
    I am developing a component which shall switch from JFormattedField to JComboBox as per requirements. For example, If a single value is used then the component acts like a JFormattedTextField and if array of values is used then the component acts like a JComboBox.
    One way of doing this is to create a new class sub-classing JComponent, create both the above mentioned objects and then implement all the methods (inherited as well as sum of methods/properties of both the components) by forwarding the call to the JFormattedTextField or JCombobox or both.
    Can somebody suggest a better design.
    Thanks in advance! Good day!
    RKON

    almost2good wrote:
    How can I make Lion show a space number on the top of the screen so I can see which space I am in?
    Currently you cannot.
    almost2good wrote:
    How can I make Lion switch spaces in a ring? ie? 1, 2, 3, 4, 5, 6, 1, 2, 3,  ...
    You cannot organise Mission Control's "Desktops" this way. They are organised in a single row to allow the swipe gestures to work. Apple allows no way to customise this.
    almost2good wrote:
    How can I make lion switch directly to a numbered space?  ie: 1, 4, 5, 2, etc...
    By deafult you should be able toi switch by pressing ctrl plus the desktop number, e.g. ctrl+1. This is the same as Spaces in Snow Leopard. You can customise this under System Preferences (Keyboard > Keyboard Shortcuts > Mission Control).
    almost2good wrote:
    Without these three capabilities Mission Control is a giant step backward....I am disappointed in the way it works and would liketo know how to disable it and give me back the way spaces used to work.
    A lot of people are disapointed with Mission Control. In my opinion it's a step backwards from Spaces & Expose in Snow Leopard but peoples views on this will depend if they used Spaces & Expose in Leopard/Snow Leopard and the type of Mac they are using - it makes some sense on a Macbook Air, for example, with a small screen and multi-touch trackpad but not so much on an iMac or Mac Pro (sames goes for Launchpad). I just hope Apple listens to the criticism and enables customisation options to change the way Mission Control behaves.

  • 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);

Maybe you are looking for

  • IPod 4 freezing, losing internet connection. Is there any way to fix this?

    My iPod 4 is only six months old, but hasn't been working well recently. Some apps have been saying i dont have internet connection, when i have all 3 signal bars. Then today, it froze up. I restarted it with the Home and Sleep buttons, and then it f

  • Cannot find any information on property

    I'm running tomcat 4.1. I have created one simple bean. When I tried to run a JSP page containing getProperty JSP tag, I got this message: Cannot find any information on property 'Message' in a bean of type 'SimpleBean'. What could have gone wrong?

  • Java Mail Problems within JSP Page

    Hi all, I'm encountering the following problem. I hava a jsp file named common.jsp with holds all common functions like write header and footer and also a send mail function. i include this page in all my other jsp pages. In the signup page - i need

  • Problem with Integrating Ejbs

    Hai, I am trying to integrate all the ejbs into single ear. its fine upto 8 ejb projects, but while trying to add another project ,its giving the error: The error details are: Caught exception during application deployment from SAP J2EE Engine's depl

  • Canon HG10 -Can't tranfter footages using log and transfer

    I'm trying to transfer from canon HG10.Log and transfer not reconising the videos.Any solution please. GUna