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.

Similar Messages

  • JFormattedTextField/focus problem

    I have a small form with 3 JFormattedTextFields for input numbers and one JLabel as a total, all are subclassed with custom code.
    I use input verify in with the JFormattedTextFields to call a method in the JLabel to create a total.
    The problem is that I update one of the number keys and tab to the next field. The total label does not change. If I then tab to the 3rd field (without changing any data) and the total label now updates with the proper total. So the total field will not update on the first focus transfer but does no the second one.
    To make it more interesting, if I use the cursor to change field focus, the update occurs immediately.
    What is different about changing focus with the mouse and tab key?
    Regards, bucky pope

    I have a small form with 3 JFormattedTextFields for input numbers and one JLabel as a total, all are subclassed with custom code.
    I use input verify in with the JFormattedTextFields to call a method in the JLabel to create a total.
    The problem is that I update one of the number keys and tab to the next field. The total label does not change. If I then tab to the 3rd field (without changing any data) and the total label now updates with the proper total. So the total field will not update on the first focus transfer but does no the second one.
    To make it more interesting, if I use the cursor to change field focus, the update occurs immediately.
    What is different about changing focus with the mouse and tab key?
    Regards, bucky pope

  • DeFaultFormatterFactory - problems

    Hi Guys,
    I am trying to use the "DefaultFormatterFactory" on the JFormattedTextField, the problem is when i add PropertyChangelistener to it and try to change the value from say 120 to null( by clicking the backspace key) , it is going to put back the 120.00 again inthe field. How to all user to clear the value in the text field. The code used is show below. Please suggest what to do with this issue.
    Thanks
    Nicedude
    import java.awt.FlowLayout;
    import java.awt.GraphicsConfiguration;
    import java.awt.HeadlessException;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.NumberFormatter;
    public class PropertChangeListenerTest extends JFrame implements
            PropertyChangeListener {
        JFormattedTextField tf1,tf2;
        private NumberFormat othersDisplayFormat, othersDefaultFormat, othersEditFormat, nullFormat;
        private DefaultFormatterFactory otherFormatFactory;
         * @throws HeadlessException
        public PropertChangeListenerTest() throws HeadlessException {
            super();
            // TODO Auto-generated constructor stub
         * @param gc
        public PropertChangeListenerTest(GraphicsConfiguration gc) {
            super(gc);
            // TODO Auto-generated constructor stub
         * @param title
         * @throws HeadlessException
        public PropertChangeListenerTest(String title) throws HeadlessException {
            super(title);
            setUpFormats();
            tf1 = new JFormattedTextField();
            tf1.addPropertyChangeListener("value", this);
            tf1.setName("tf1");
            tf1.setFormatterFactory(otherFormatFactory );
             tf2 = new JFormattedTextField();
             tf2.setName("tf2");
             tf2.setFormatterFactory(otherFormatFactory);
            tf2.addPropertyChangeListener("value",this);
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.add(tf1);
            panel.add(tf2);
            getContentPane().add(panel);
            pack();
            setVisible(true);
         * @param title
         * @param gc
        public PropertChangeListenerTest(String title, GraphicsConfiguration gc) {
            super(title, gc);
            // TODO Auto-generated constructor stub
        /* (non-Javadoc)
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
        public void propertyChange(PropertyChangeEvent evt) {
            Object source = evt.getSource();
            Object oldValue = evt.getOldValue();
            Object newValue = evt.getNewValue();
            if(oldValue == null && newValue == null)
                return;
            System.out.println(((DETextField)source).getName() + "  oldValue: " + oldValue + "   " + "newValue : " + newValue);
            if(source == tf1){
                if(oldValue == newValue){
                    System.out.println("tf1 value not changed");
                }else{
                    System.out.println("tf1 value changed");
            }else if(source == tf2){
                if(oldValue == newValue){
                    System.out.println("tf2 value not changed");
                }else{
                    System.out.println("tf2 value changed");
         * @param args
        public static void main(String[] args) {
            PropertChangeListenerTest test = new PropertChangeListenerTest("Test");
        private void setUpFormats(){
            othersDisplayFormat = new DecimalFormat();
            othersDisplayFormat.setMinimumFractionDigits(2);
            othersDisplayFormat.setMaximumFractionDigits(2);
            othersDefaultFormat = new DecimalFormat();
            othersDefaultFormat.setMinimumFractionDigits(2);
            othersDefaultFormat.setMaximumFractionDigits(2);
            othersEditFormat = new DecimalFormat();
            othersEditFormat.setMinimumFractionDigits(2);
            othersEditFormat.setMaximumFractionDigits(2);
            otherFormatFactory = new DefaultFormatterFactory(
                    new NumberFormatter(othersDefaultFormat),
                    new NumberFormatter(othersDisplayFormat),
                    new NumberFormatter(othersEditFormat));
    }

    Take a look at [url http://forum.java.sun.com/thread.jspa?forumID=57&threadID=475909&start=5]this thread.

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

  • 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

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

  • Problem with a mask in a JFormattedTextField

    I am tring to create a text box with a mask.
    This object text box is declared like a class var.
    I have another object, a mask object that is also declared as a class var
    but I cant create this mask. The errors are commented,
    if you erase the comments and create the class you are going to see the error.
    javac ContraBase.java
    java ContraBase
    Estoy tratando de crear un campo de texto con mascara.
    este objeto texto esta definico como variable de clase
    tengo definida una mascara tambien como variable de clase
    Pero no me deja crear la mascara. Los errores estan comentados,
    si quita los comentados y crea el class vera el problema.
    javac ContraBase.java
    java ContraBase
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.JFormattedTextField;
    class ContraBase extends JPanel
         //MaskFormatter mascara1 = new MaskFormatter("########"); //aca se produce un error
         //JFormattedTextField PRECIOA = new JFormattedTextField (mascara1); //la idea es definir aca la mascara
         JFormattedTextField PRECIOA = new JFormattedTextField ("########");
         public ContraBase()
              //TEXTBOX
              PRECIOA.setToolTipText("PRECIOA");
              add(PRECIOA);
         static public void main (String[] args)
              System.out.println("Iniciando programa.");
              try
                   JFrame VentanaPrincipal = new JFrame("Practicas con Java, trabaja con Base");
                   VentanaPrincipal .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   VentanaPrincipal .getContentPane().add(new ContraBase(), BorderLayout.CENTER);
                   VentanaPrincipal .setSize(350,500);
                   VentanaPrincipal .setVisible(true);
              catch(Exception e)
                   System.out.println("****INGRESA A EXCEPTION main****");
                   System.out.println(e.toString());
                   System.out.println("****SALE DE EXCEPTION main****");
                   return;
              System.out.println("Creacion Finalizada.");
    }

    Sounds like that field is editable. The renderer renders the display when a field is not
    being edited, a TableCellEditor is in charge when the field is edited, and the default
    editor is just a JTextField.
    : jay

  • Problems with MaskFormatter and JFormattedTextfield

    Hi,
    I'm new to the forum and Java programming so if anyone is willing to answer this query with a small degree of patience I would be immensely, humbly grateful!
    I'll say firstly that I wrote the program in jdk1.4.2 then recompiled it in 1.6.0 in the vain hope that the problem would go a way, but no such luck.
    Right, I'm using one Formatted textfield with a MaskFormatter on which I change the mask according to what information I want from the user:
    class myFormatter extends MaskFormatter {
              String key;
              public void setMask(String k){
                   key = k;     
                   if (key.equals("text")) {
                        try{
                             super.setMask("*************"); // for text, eg star names
                             super.setValidCharacters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("num")) {
                        try{
                        super.setMask("****#"); // for numbers 1-10000 eg frame num
                                    super.setValidCharacters("0123456789\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("epoch")) try{
                        super.setMask("####.#"); // for epoch
                        super.setValueContainsLiteralCharacters(true);
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("yna")) try{
                        super.setMask("L"); // for single lower case characters eg y/n/a
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("coord")) try{
                        super.setMask("*## ## ##"); // for RA/Dec
                        super.setValueContainsLiteralCharacters(true);
                        super.setValidCharacters("0123456789+-\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("reset")) try{
                        super.setMask("*********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else  try{
                        super.setMask("********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
    -----------------------------------------------------------------------------------------------------Ok, now I've only gotten as far as checking the implementation of the "epoch", "text", "yna" and "coord" keys. I've discovered two main problems:
    1. The A, ? and H masks in MaskFormatter just simply did not work; the textfield would not let me enter anything, even when setting the valid the characters, hence having to use * for implementing the "text" key.     
    But most importantly:
    2. The "coord" mask will not let me enter anything (example coordinates -32 44 55) and when I try (in particular press the backspace to start entering at the beginning of the ttextfield instead of the middle, where the cursor is put) I presented with this horrendous complaint from the compiler:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.text.MaskFormatter.isLiteral(MaskFormatter.java:566)
    at javax.swing.text.MaskFormatter.canReplace(MaskFormatter.java:711)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:560)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:533)
    at javax.swing.text.DefaultFormatter$DefaultDocumentFilter.remove(DefaultFormatter.java:711)
    at javax.swing.text.AbstractDocument.remove(AbstractDocument.java:573)
    at javax.swing.text.DefaultEditorKit$DeletePrevCharAction.actionPerformed(DefaultEditorKit.java:1045)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2844)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2879)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2807)
    at java.awt.Component.processEvent(Component.java:5815)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:693)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:958)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:830)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:657)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    A NullPointerException??? I even tried priming the textfield by setting the value using formatTxt.setValue(format.stringToValue("+00 00 00")).
    Does anyone have any ideas on this error (or how I can get around this without delving to much into other filtering classes)? Has anyone had similar problems with the MaskFormatter masks not accepting what they claim they do (I looked through the posts on the subject).
    Thanking you in advance for you patience........

    Hi,
    Thank you very much for your prompt reply.
    I've done as you said - written a smaller program to test each mask. They don't work quite as I expected but you're right, each mask works fine, its changing the masks that's the problem. I wrote this to test it out:
    public class testMask {
    //Note:      main() won't let u access object/variable methods if declared here
    // GUI items to be globally accsessed:
         JFrame MainWin;
         JPanel panel, panel1;
         JLabel question, answer;
         JButton send, askQues, change;
         JFormattedTextField formatTxt;
         myFormatter format;
    // I/O to be globally accessed:
         String usrinput = null;
         public static void main( String[] args ) {
              testMask GUI = new testMask();
         public testMask(){
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public synchronized void run() {
                              create();
                 });                              //     thread safe code to make sure that UI painting is not interrupted by events, possibly causing the UI to hang
         public synchronized void create(){
              //set look and feel of GUI
              try {
              } catch (Exception e) {
                             System.out.println("Error - Problem displaying window");
              //initialise main window and set layout manager
              MainWin = new JFrame("Test Masks");     
              MainWin.getContentPane().setLayout(new BorderLayout());     
              // initialise containers to go on MainWin
              panel = createPanel();
              MainWin.getContentPane().add(panel, BorderLayout.CENTER);
              MainWin.pack();
              MainWin.setSize(300,150);
              MainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              MainWin.setLocation(150, 150);
              MainWin.setVisible(true);
         public synchronized JPanel createPanel() {
              JPanel panel1 = new JPanel();
              panel1.setLayout(new GridLayout(3,1));
              Border border = BorderFactory.createEtchedBorder();
              panel1.setBorder(BorderFactory.createTitledBorder(border, " Test Panel "));
              question = new JLabel("Please enter drive");
              answer = new JLabel();
              answer.setBorder(border);
              panel1.add(question);
              JPanel pane1 = new JPanel(new FlowLayout());
    //------Set up formatted textfield for user input to be verified--------
              format = createFormatter();
              format.setMask("drive");
              formatTxt = new JFormattedTextField(format);
              formatTxt.setColumns(10);
              send = new JButton(" Send ");
              send.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              send.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        try{
                             formatTxt.commitEdit();
                        } catch (java.text.ParseException exc) {
                             answer.setText("Problem with formatting: " + exc.getMessage());
                             return;
                        SwingUtilities.invokeLater(new Runnable() {
                             public synchronized void run() {                         
                                  if (formatTxt.isEditValid()) {
                                       usrinput = formatTxt.getText();
                                       answer.setText(usrinput);
                                  } else { answer.setText("Input not of valid format"); }
              change = new JButton("Change mask");
              change.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              change.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        question.setText("Please enter coord in format ## ## ##");
                        format.setMask("coord");
              pane1.add(formatTxt);
              pane1.add(send);
              pane1.add(change);
              panel1.add(pane1);
              panel1.add(answer);
              return panel1;
         protected myFormatter createFormatter() {
              myFormatter formatter = new myFormatter();
              return formatter;
    class myFormatter extends MaskFormatter {
         String key;
         public void setMask(String k){
              key = k;     
              if (key.equals("coord")) {
                   try{
                        super.setMask("*## ## ##"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else if (key.equals("drive")) {
                   try{
                        super.setMask("L:"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else  {
                   try{
                        super.setMask("********************"); // accept anything
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
    }When I click on the "change" button, the textfield won't let me enter anything in, no matter what I change the mask from or to.
    Does anyone have any idea how I can implement the mask change dynamically? The only thing I could think of was to somehow re-initalise the textfield then do a repaint, but I don't know how or if that would even work.
    Thanking you again in anticipation,
    Mellony

  • Problem with co-existence JFormattedTextField and JButton

    When I use three JFormattedTextField (exactly - my own classes extending JFormattedTextField) and several JTextField I get a problem - the JButton (that changes it's enabling in dependence of field's content) work only after third click. When I use JTextField instead of JFormattedTextField, all works fine.

    my own classes extending JFormattedTextFieldWell, first you test it using the standard classes to see if it works. If it does then you know the problem is with your custom code.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

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

  • JFormattedTextField Problem

    i want to put a jFormattedTextField and i do the following
    private JFormattedTextField field;
    public JinternalFrame method() {
    // I declare the jInternalFrame and jPanel
    field = new JFormattedTextField();
    field.setValue(new Number(6));
    //and after I add it into the jPanel
    }//end method
    I take an error java.lang.Number is abstract; cannot be instantiated
    I use the Java2 v1.4.2

    Of course you have this exception, because the java.lang.Number is abstract.
    You need to use some next constructions:
    field.setValue(new Integer(6)); or field.setValue(new Double(6));
    or if you want with java.lang.Number :
    Number num = new Integer(6)
    field.setValue(num);
    I hope, that will help you.

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

  • Problem with PropertyChangeListener and JTextField

    I'm having a problem with PropertyChangeListener and JTextField.
    I can not seem to get the propertychange event to fire.
    Anyone have any idea why the code below doesn't work?
    * NewJFrame.java
    * Created on May 15, 2005, 4:21 PM
    import java.beans.*;
    import javax.swing.*;
    * @author wolfgray
    public class NewJFrame extends javax.swing.JFrame
    implements PropertyChangeListener {
    /** Creates new form NewJFrame */
    public NewJFrame() {
    initComponents();
    jTextField1.addPropertyChangeListener( this );
    public void propertyChange(PropertyChangeEvent e) {
    System.out.println(e);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
    jFormattedTextField1.setText("jFormattedTextField1");
    jScrollPane1.setViewportView(jFormattedTextField1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    }

    If you want to listen to changes in the textfield's contents you should use a DocumentListener and not a PropertyChangeListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
    And please use [co[/i]de]  tags when you are posting code (press the code button above the message window).

  • 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

Maybe you are looking for

  • After update 10.5.6 error UserEventAgent [184]

    I'm just getting UserEventAgent [184] error, several times. Process: UserEventAgent [184] Path: /usr/sbin/UserEventAgent Identifier: UserEventAgent Version: ??? (???) Code Type: X86 (Native) Parent Process: launchd [174] Date/Time: 2008-12-18 11:00:2

  • How can I type different languages for imovie title?

    Im trying to create a tittle in Thái ? How can I do that? I have no problem typing in English. Thanks

  • FileDownload from Content-Server (Knowledge Provider)

    Hi, I am trying to download a File via FileDownload UI from the Conent-Server. The Files are from Type: Knowledge Provider (KPro).  I get the following InputStream (Character from 01-12 + Binary from 13-17) : I need only the binary part, the lines fr

  • Export Logical Schema

    How can we export logical schema.

  • Macromedia Flash8 and Adobe Flash CS3 compatibility.

    I have macromedia Flash8 and am trying to open and edit Adobe Flash CS3 template and getting an unexpected file format error message. Are these softwares compatible or is there anything that I can do to enable me open and edit Adobe Flash CS3 templat