JFormattedTextField with setDefaultButton

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

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

Similar Messages

  • JFormattedTextField with different format

    Hi...
    I need a JFormattedTextField with different format.
    I need validate that user can type anybody previous format.
    I have looked several example code in the forum, but none it is successfully for me?
    What do you advise to do? Please with an example is better.
    Thank you

    Hi JayDS.
    I had reviewed your VariableLengthMaskFormatter class.
    I don't know if it's good for me.
    When the user begins to type I don't know the format that he'll use.
    When the JText focus lose then I knew the format that user used.
    What can I do?

  • JFormattedTextField with Optional Characters

    Hey All!
    I'm working on a project to manage my church's congregational phone book and have it up to basic functionality, i.e., reading the database, allowing addition of new entries and modification of existing entries, etc.
    I'm using a jFormattedTextField for the input field of the Zip Code, phone number, birthdate and anniversary date. Using this widget for the phone, Zip Code and birth date are no problem, but for the anniversary date field, I have a question.
    Sometimes a member wants to have the year that they were married included in their anniversary date and sometimes they don't. How can I set up the formatter for the jFormattedTextField to accept and display the year, if it is entered, but not require the year to be entered?
    For example, some entries in the spreadsheet that I'm converting look like this:
    LastName   FirstName  Phone #            Address                                   Birth           Anniversary
    Smith      John       346-1234           123 Main Street, Pekin, IL 61554          October 24      August 12, 1968
    Smith      Margaret   346-1234           123 Main Street, Pekin, IL 61554          April 12        August 12, 1968
    Jones      Mac        346-9876           1005 George Street, Pekin, IL 61554       June 1          November 8
    Jones      Michelle   346-9876           1005 George Street, Pekin, IL 61554       September 1     November 8Though names, addresses and phone numbers have been changed to protect the innocent and guilty alike, this is a true example of what I've got to work with. As you can see, sometimes I have the year of marriage and sometimes not (mostly not). Is there a way to set the formatter for the JFormattedTextField up to accept the year on the date, but not require it to be entered and not zero-fill the year if it is not entered. For example, if I enter the date of August 12, 1968 into the field, it would display it just as entered...no problem. But, if I enter the date of November 8 into the field, I want it to display it just as I entered it, not delete the text because there's no year and not display it as November 8, 0000. Any way to accomplish this?
    I look forward to any and all pointers that you can provide. In the interim, I will continue Googling to see what I can find, even though the pickings are pretty slim with my searches.
    Cheers,
    Sean Carrick
    PekinSOFT Systems

    Thanks, camickr...I'll give that a try. Just seems kind of strange that I can't simply set up a custom mask on the jFormattedTextField...
    Back in the days before I gained a higher insight into what constituted a good system and good programming (i.e., before I reached my age of enlightenment) and still used MS Windows, and programmed in Visual Basic, I was able to do just what I'm trying to do using the MaskedEditBox in VB. It seemed such a simple thing to implement. I figured that the jFormattedTextField would have some similarities (albeit much improved functionality) with the VB MaskedEditBox.
    Anyway, I'll look into your suggestion using a jTextField, InputVerifier and, possibly, a DocumentFilter. Should be an interesting learning experience at the absolute least.
    Cheers,
    Sean Carrick
    PekinSOFT Systems

  • JFormattedTextField with edit and display formatter for date

    How can I have a date display formatter and a edit mask date formatter for JFormattedTextField instance.
    When I do
                   DateFormatter dateFormatter = new DateFormatter(new SimpleDateFormat("dd/MM/yyyy"));
                   JFormattedTextField.AbstractFormatterFactory factory = new DefaultFormatterFactory(dateFormatter, dateFormatter, dateFormatter);
                   jFormattedTextField_2.setFormatterFactory(factory);
    all is okie but I wanna a mask formatter and if I do
                   DateFormatter dateFormatter = new DateFormatter(new SimpleDateFormat("dd/MM/yyyy"));
                   MaskFormatter editFormater = new MaskFormatter();
                   try {
                        editFormater.setMask("##/##/####");
                   } catch (ParseException e) {
                        e.printStackTrace();
                   editFormater.setPlaceholderCharacter('_');               
                   JFormattedTextField.AbstractFormatterFactory factory = new DefaultFormatterFactory(dateFormatter, dateFormatter, editFormater);
                   jFormattedTextField_2.setFormatterFactory(factory);
    jFormattedTextField_2 accepts invalid date.
    What can I do to have a date edit mask and a date display mask for a
    JFormattedTextField instance.
    Thx a lot, Tony.

    txtdatnalzaproizvoid = new JFormattedTextField(datformater("##/##/##"));
    txtdatnalzaproizvoid.setValue(datumformat());
    public static MaskFormatter datformater(String formatnavnes){
    MaskFormatter formatter = null;
    try {
    formatter = new MaskFormatter(formatnavnes);
    formatter.setValidCharacters("0123456789");
    } catch (java.text.ParseException exc) {
    System.err.println("formatter is bad: " + exc.getMessage());
    System.exit(-1);
    return formatter;
    public static String datumformat(){
    Date dddd = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
    datumformat = formatter.format(dddd);
    return datumformat;
    }

  • JFormattedTextField with a regex formatter

    If I pass the formatter to the JFormattedTextfield as follows:
    new JFormattedTextField(new RgxFormatter(aFormatter)
    Is input validated as characters are entered or what other verification is required if needed? How?
    Thanks to all for help.

    Hi,
    new JFormattedTextField(new RgxFormatter(aFormatter)Is this a formatter of your own?

  • Strange thing happens with JTable & JFormattedTextField

    hello,
    again a problem,
    in my Jtable i have different JFormattedTextField with a mask for a datefield, everything works fine, for that i made a formatteddateeditor which holds a JFormattedTextField an a renderer which extends a JFormattedTextField and implements the tablecellrenderer.
    Now here 's my problem, sometimes when i click on so a field, the mask (__/__/___) dispappears and i got a blank field with the cursor blinking,does anaybody knwo how to do solve this thing ???
    THX
    Tom

    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

  • 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 to use  JtextFild with java.util.Date;

    hi
    My problem is that i have a date data type field inaccess in table.
    Otherside i use JTextField.
    First when this window show i initialize this field with current date.
    The code for this is
    lbdate = new JLabel("User Date",JLabel.RIGHT);
              lbdate.setBorder(new EtchedBorder());     
              txtdate = new JTextField();
              txtdate.setBorder(BorderFactory.createLineBorder(Color.red));
              //month convert into string
              int m = cal.get(Calendar.MONTH);
              m++;
              String mon = Integer.toString(m);
              //day convert into string
              int d = cal.get(Calendar.DATE);
              String date = Integer.toString(d);
              //year convert into string
              int y = cal.get(Calendar.YEAR);
              String year = Integer.toString(y);
              txtdate.setText(mon+" / "+date+" / "+year);
    i am not satisfied by this. How can initialize the JtextField by some other method.
    The secound part of question is that how to reterive the date data type of field and see in the textfield.I see butt it returns like this year/month/date(this date is coming from database which already input) 00:00:00
    How can i discard 00:00:00(this time)
    I code for this is
    Date date = rs.Date();
    txtfld.setText(date); //Here error is occured of TypeCasting
    and tell me that how date type object can convert into String for set the text of field
    because JTextField only accept the String data.
    (if u illestrate with code).
    thanks

    Use a JFormattedTextField with a SimpleDateFormat in parameter.
    Denis

  • JFormatted with valid date

    halo.....
    i have a JFormattedTextField with MaskFormatted represent date. the maskformatted is like ("## / ## / ####") without space actually. its for dd/mm/yyyy. but when i want to save to ms access DB, it can have like day 32 or more and month 13 or more.
    what i want is, can i limit the day or month so when someone input the date that out of range, it show something error-like...
    thanks....

    you have used this line of code
    try
    Date dat = format.parse(you TextField.getText());
    catch(Exception e)
    JOptionPane.showMessageDialog(null,"Invalid Date", "Error", JOptionPane.ERROR_MESSAGE);     
    if you enter month above 12 or day above 31 it will not parsing

  • JFormattedTextField using NumberFormatter

    Hi.
    I have a textfield that is supposed to accept numbers from 0 to 10000. I am using a JFormattedTextField, with a NumberFormatter. I am setting setAllowsInvalid(false) sinse i don't want the user to be abel to enter a number greater than 10000. The problem is, when I enter something in the textfield, I want to be able to erase what is there first and then enter my new value instead of having to overwrite the existing values. That is, I want to be able to backspace to an empty textfield and, not be able to enter characters other than numbers between 0 and 10000 at the same time. Right now, when I backspace, it doesn't let me eliminate the last character. How do i solve this problem?

    I don't really understand what you are asking but if you want to accept values between 0 to 10000. Then I would think you would want to use a JSpinner instead:
    http://java.sun.com/docs/books/tutorial/uiswing/components/spinner.html

  • JFormattedTextField auto fill

    This is kind of hard for me to explain so bare with me. I have a program that reads from the JFormattedTextField (with fieldname.gettext() call). The formatter for the field is this:
         static protected MaskFormatter cformatter(String s){
              MaskFormatter formatter = null;
              try {
                   formatter = new MaskFormatter(s);
              } catch (ParseException e) {
                   e.printStackTrace();
              return formatter;
         }and my call to the JFormattedTextField is: new JFormattedTextField(cformatter("##"));
    well anyway I read from the field 3 times and after you type in what you need the first time i use the call fieldname.settext("") to erase everything in the field and it does but what my problem is when I go outside the field and click on something else ("disselect" the field) the previous numbers appear from the first time I typed in the field even though I "erased" it. Is there a way to fix this problem?

    Just a guess(*), but are you calling [setFocusLostBehavior()|http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.html#setFocusLostBehavior(int)] so that the text field does the right thing? (Whatever that is: possibly JFormattedTextField.PERSIST and certainly not JFormattedTextField.REVERT which seems to be the behaviour you describe.)
    Also, I note there's a [commitEdit()|http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.html#commitEdit()] method which sounds like it might need to be called after setText() so that the empty string becomes the valid Object that getValue() would return.
    (*) For less guesswork and more authoratative help on JFormattedTextField, there's the [Swing Forum|http://forums.sun.com/forum.jspa?forumID=57&start=0].
    Edited by: pbrockway2 on Dec 19, 2008 3:58 PM
    The default behaviour for these things is JFormattedTextField.COMMIT_OR_REVERT. And since your empty string is not a valid value for the text field, it reverts.

  • Problems with JFormatedTextField and backspace( aka bug 4678007)

    Hi guys,
    did anybody find workaround for bug# 4678007 when backspace does not work properly for JFormattedTextField with NumberFormatter?
    Below my custom class.
    Thanks in advance.
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.JFormattedTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.NumberFormatter;
    public class AmountTextField extends JFormattedTextField
         public static final String s_strAmountFormat = "$#,###,##0.00";     
         public AmountTextField()
              this(new Double(0.0));
         public AmountTextField(Object value)
              super(getAmountFormatter());               
              setupAmountField();          
              setValue(value);     
         public static DecimalFormat getFormat()
              return new DecimalFormat(s_strAmountFormat);
         public static NumberFormatter getAmountFormatter()
    //          DecimalFormat amountFormat =  getFormat();
              NumberFormat amountFormat =
                     NumberFormat.getCurrencyInstance();
              amountFormat.setParseIntegerOnly(false);
              NumberFormatter formatter = new NumberFormatter(amountFormat);     
              formatter.setAllowsInvalid(false);
              formatter.setCommitsOnValidEdit(true);
    //          formatter.setOverwriteMode(true);
              formatter.setValueClass(Double.class);          
              formatter.setMinimum(new Double(0.0));          
              return formatter;
         private void setupAmountField()
                   addFocusListener(new FocusListener()
                        public void focusGained(final FocusEvent e)
                             final AmountTextField txtField = (AmountTextField)e.getSource();
                             SwingUtilities.invokeLater(new Runnable()
                                                 public void run()
                                                      int nPos = Math.max(0, (txtField.getText()).toString().length() - 3);
                                                      System.out.println("Caret position = " + nPos);
                                                      txtField.setCaretPosition(nPos);
                                                      txtField.moveCaretPosition(1);
                        public void focusLost(FocusEvent e)     {}                    
              setHorizontalAlignment(RIGHT);
              setColumns(s_strAmountFormat.length());          
         public void setMaxAcceptableValue(Double dblValue)
              AbstractFormatter formatter = getFormatter();
              if (formatter instanceof NumberFormatter)
                   ((NumberFormatter)formatter).setMaximum(dblValue);
         public void setMinAcceptableValue(Double dblValue)
              AbstractFormatter formatter = getFormatter();
              if (formatter instanceof NumberFormatter)
                   ((NumberFormatter)formatter).setMinimum(dblValue);
    import javax.swing.BoxLayout;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class AmountFieldTest extends JPanel
         //Text fields for data entry
         private AmountTextField amountField1;
         private AmountTextField amountField2;
         private AmountFieldTest()
              super();
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              amountField1 = new AmountTextField();
              add(amountField1);
              amountField2 = new AmountTextField(new Double(1234567.99));
              add(amountField2);          
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new JFrame("AmountFieldTest");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              JComponent newContentPane = new AmountFieldTest();
              newContentPane.setOpaque(true);
              frame.setContentPane(newContentPane);
              frame.pack();
              frame.setVisible(true);
    }

    Hi guys,
    did anybody find workaround for bug# 4678007 when backspace does not work properly for JFormattedTextField with NumberFormatter?
    Below my custom class.
    Thanks in advance.
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.JFormattedTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.NumberFormatter;
    public class AmountTextField extends JFormattedTextField
         public static final String s_strAmountFormat = "$#,###,##0.00";     
         public AmountTextField()
              this(new Double(0.0));
         public AmountTextField(Object value)
              super(getAmountFormatter());               
              setupAmountField();          
              setValue(value);     
         public static DecimalFormat getFormat()
              return new DecimalFormat(s_strAmountFormat);
         public static NumberFormatter getAmountFormatter()
    //          DecimalFormat amountFormat =  getFormat();
              NumberFormat amountFormat =
                     NumberFormat.getCurrencyInstance();
              amountFormat.setParseIntegerOnly(false);
              NumberFormatter formatter = new NumberFormatter(amountFormat);     
              formatter.setAllowsInvalid(false);
              formatter.setCommitsOnValidEdit(true);
    //          formatter.setOverwriteMode(true);
              formatter.setValueClass(Double.class);          
              formatter.setMinimum(new Double(0.0));          
              return formatter;
         private void setupAmountField()
                   addFocusListener(new FocusListener()
                        public void focusGained(final FocusEvent e)
                             final AmountTextField txtField = (AmountTextField)e.getSource();
                             SwingUtilities.invokeLater(new Runnable()
                                                 public void run()
                                                      int nPos = Math.max(0, (txtField.getText()).toString().length() - 3);
                                                      System.out.println("Caret position = " + nPos);
                                                      txtField.setCaretPosition(nPos);
                                                      txtField.moveCaretPosition(1);
                        public void focusLost(FocusEvent e)     {}                    
              setHorizontalAlignment(RIGHT);
              setColumns(s_strAmountFormat.length());          
         public void setMaxAcceptableValue(Double dblValue)
              AbstractFormatter formatter = getFormatter();
              if (formatter instanceof NumberFormatter)
                   ((NumberFormatter)formatter).setMaximum(dblValue);
         public void setMinAcceptableValue(Double dblValue)
              AbstractFormatter formatter = getFormatter();
              if (formatter instanceof NumberFormatter)
                   ((NumberFormatter)formatter).setMinimum(dblValue);
    import javax.swing.BoxLayout;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class AmountFieldTest extends JPanel
         //Text fields for data entry
         private AmountTextField amountField1;
         private AmountTextField amountField2;
         private AmountFieldTest()
              super();
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              amountField1 = new AmountTextField();
              add(amountField1);
              amountField2 = new AmountTextField(new Double(1234567.99));
              add(amountField2);          
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new JFrame("AmountFieldTest");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              JComponent newContentPane = new AmountFieldTest();
              newContentPane.setOpaque(true);
              frame.setContentPane(newContentPane);
              frame.pack();
              frame.setVisible(true);
    }

  • PatternSyntaxException: Dangling meta character '*' near index 0

    Hi,
    I am using DocumentFilter to control the input in a JtextField In accordance with model of a mask.
    The mask can contain the following characters:
        //  # :  for  =---> NUMBER only
        //  ? :  for  =---> LETTER only
        //  A :  for  =---> LETTER end for NUMBER
        //  * :  for  =---> ANYTHING    I made a class that extends DocumentFilter and it look like this:
    public class MydocumentFilter extends DocumentFilter {
    public void insertString(...){
    // do anything
        } // insertString()
    public void remove(...)
    // do anything
        } // remove()
    @Override
        public void replace(
                DocumentFilter.FilterBypass fb,
                int offset, // posizione del cursore
                int length, // Length of text to delete (solo per sostituzioni...)
                String text,// testo da inserire
                AttributeSet attrs) throws BadLocationException {
    // here are some controls that change the value of the text variable, and at last call the super class..:
            super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);
        } // replace()
    } // class  MydocumentFilterI have a problem when the user write wildcards (='*' OR '?').
    Then I get the message:
    Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0.I know that '*' and “?” are is a metachars and for that I added this code before calling super.replace(...);
            if (text.compareTo("*") == 0){
                replace = "\\*";
            }but I don't get the expected result. I get -\*- instead then -*-
    here the code of the program that I use to make tests:
    * http://www.java2s.com/Tutorial/Java/0260__Swing-Event/CustomDocumentFilter.htm
    * @author Owner
    //public class IntegerRangeDocumentFilter extends DocumentFilter {
    public class NavBean_documentFilter extends DocumentFilter {
        enum CharAcceptability_ENUM {
            valid, invalid, overrite
        String mask;
        public NavBean_documentFilter(String mask_) { // constructor
            mask = mask_;
        } // constructor
        @Override
        public void insertString(
                DocumentFilter.FilterBypass fb,
                int offset,
                String string,
                AttributeSet attr) throws BadLocationException {
            System.out.println("insert string" + string);
            System.out.println(offset);
            super.insertString(fb, offset, string, attr);
        } // insertString()
        @Override
        public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
                throws BadLocationException {
            System.out.println("remove");
            super.remove(fb, offset, length);
        } // remove()
        public void replace(
                DocumentFilter.FilterBypass fb,
                int offset, // posizione del cursore
                int length, // Length of text to delete (solo per sostituzioni...)
                String text,// testo da inserire
                AttributeSet attrs) throws BadLocationException {
            boolean valid = true;
            if (offset > mask.length()) {
                return;
            if (text.length() != 1) {
                return;
            CharAcceptability_ENUM charAcceptability_ENUM = checkTheInput(text, offset);
            String replace = null;
            switch (charAcceptability_ENUM) {
                case invalid:
                    replace = "";
                    break;
                case valid:
                    replace = text;
                    break;
                case overrite:
                    char cc = mask.charAt(offset);
                    replace = String.valueOf(cc);
                    break;
            // It is because * is used as a metacharacter to signify one or more
            // occurences of previous character.
            // So if i write M* then it will look for files MMMMMM..... !
            // Here you are using * as the only character so the compiler
            // is looking for the character to find multiple occurences of,
            // so it throws the exception.:)
            if (text.compareTo("*") == 0){
                replace = "\\*";
            text = replace;
            super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);
    //        super.replace(fb, offset, length, text, attrs);
        } // replace()
        private CharAcceptability_ENUM checkTheInput(String text, int cursorPosition) {
            if (cursorPosition >= mask.length()) {
                return CharAcceptability_ENUM.invalid;
            char mappedCharInTheMask = mask.charAt(cursorPosition); // qui erro
            char charToSet = text.charAt(0);
            System.out.println("carattere da mettere = " + charToSet + " ; carattere della maschera = " + mappedCharInTheMask);
            boolean placeHolderFree = mask.contains(String.valueOf(mappedCharInTheMask));
            if (!placeHolderFree) {
                return CharAcceptability_ENUM.invalid;
            CharAcceptability_ENUM charAcceptability_ENUM =
                    CharAcceptability_ENUM.invalid;
            char holdPlace = mask.charAt(cursorPosition);
            switch (holdPlace) {
                case '*': // 
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case '#': // only numbers
                    if ( Character.isDigit(charToSet)) {
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case '?': //only letters
                    if (Character.isLetter(charToSet)){
                        charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case 'A': // letters and numbers
                    if (Character.isLetterOrDigit(charToSet)){
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                    default:
                        charAcceptability_ENUM = CharAcceptability_ENUM.overrite;
            System.out.println("valore di charAcceptability_ENUM = " + charAcceptability_ENUM.toString());
            return charAcceptability_ENUM;
        } // checkTheInput()
    } // class UsingDocumentFilter
    class RangeSample {
        public static void main(String args[]) {
            JFrame frame = new JFrame("Range Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // questo (in generale) e' quanto si deve fare per usare un filtro...
            JTextField textFieldOne = new JTextField();
            JLabel jLabMask = new JLabel();
            JPanel panel = new JPanel();
            String explanation1 = "      ---  use of wildCard: ---";
            String explanation2 = " #  :  is for  =---> only NUMBER ";
            String explanation3 = " ?  :  is for  =---> only LETTER ";
            String explanation4 = " A  :  is for  =---> LETTER end NUMBER";
            String explanation5 = " *  :  is for  =---> ANYTHING      ";
            JLabel jLabExplanat1 = new JLabel(explanation1);
            JLabel jLabExplanat2 = new JLabel(explanation2);
            JLabel jLabExplanat3 = new JLabel(explanation3);
            JLabel jLabExplanat4 = new JLabel(explanation4);
            JLabel jLabExplanat5 = new JLabel(explanation5);
            panel.setLayout(new GridLayout(5, 1));
            panel.add(jLabExplanat1);
            panel.add(jLabExplanat2);
            panel.add(jLabExplanat3);
            panel.add(jLabExplanat4);
            panel.add(jLabExplanat5);
            jLabExplanat1.setForeground(Color.green);
            jLabExplanat2.setForeground(Color.red);
            jLabExplanat3.setForeground(Color.red);
            jLabExplanat4.setForeground(Color.red);
            jLabExplanat5.setForeground(Color.red);
            jLabMask.setForeground(Color.blue);
            //AAA-##:***
            String mask = "##-A#A:#????  ***";
    //        String mask = "***";
            Document textDocOne = textFieldOne.getDocument();
            NavBean_documentFilter filterOne = new NavBean_documentFilter(mask);
            ((AbstractDocument) textDocOne).setDocumentFilter(filterOne);
            String jLabelTxt = "mask to use :  " + filterOne.mask + "   ";
            jLabMask.setText(jLabelTxt);
            frame.setLayout(new GridLayout(3, 1));
            frame.add(panel);
            frame.add(jLabMask);
            frame.add(textFieldOne);
            frame.pack();
            frame.setLocation(300, 150);
            frame.setVisible(true);
        } // main()
    } // class RangeSampleany advice shall be appreciated
    thank you
    regards
    Angelo Moreschini

    All that many lines for a regex question (where the error message already pointed to), which has nothing to do with Swing. An SSCCE looks different.
    if (text.compareTo("*") == 0){
    replace = "\\*";
    text = replace;
    super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);You must keep the text, the regex and the replacement string apart:
    String text= "A", regEx= "A", rep= "B";
    //String text= "*", regEx="\\*", rep= "*";
    text= text.replaceAll(regEx, rep);
    System.out.println(text);And why don't you use a JFormattedTextField with a MaskFormatter which does all the job for you.

  • Date editing in a JTable

    Hello,
    whereas a JFormattedTextField with a mask formatter can be used as editor in a
    JTable just like in a container, a JFormattedTextField with a date formatter
    obviously cannot. The tutorial warns us that table cells are NOT components,
    but in what cases do we have to care?
    I also understand the tutorial in the way that while editing, the editor is
    responsible for displaying the cell, and the cell renderer takes over again
    when editing is stopped. Is that right? If yes, I would not have to care for
    a special renderer, for I'm quite happy with the default one.
    I'm trying to use a JFormattedTextField which would, if working, need only
    little code, for the solutions I found in the net are quite expanded.
    The code below is in many ways defective:
    1) Without renderer
    When editing of the date column starts, the date is displayed in the
    "dow mon dd hh:mm:ss zzz yyyy" form, and doesn't revert even when no edits
    are performed. This doesn't happen if the JFormattedTextField is used
    outside a table.
    2) With renderer
    The value arrives in the renderer sometimes as Object, sometimes as String
    (I suppose the editor is responsible for that.)
    But before I pursue this approach I would like to ask you, whether you
    generally discourge using a JFormattedTextField in a date column.
    If not, please comment my understanding and direct me to a solution.
    import java.awt.*;
    import java.text.*; // ParseException
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*; // MaskFormatter
    import javax.swing.table.*;
    public class FTFTable extends JFrame {
      public FTFTable() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);
        setTitle("FTFTable");
        Container cp = getContentPane();
        String headers[] = {"Date", "Mask: #-##"};
        DateFormat format= new SimpleDateFormat("dd.MM.yyyy");
        DateFormatter df= new DateFormatter(format);
        JFormattedTextField ftfDate= new JFormattedTextField(df);
        MaskFormatter mf1= null;
        try {
          mf1= new MaskFormatter("#-##");
          mf1.setPlaceholderCharacter('_');
        catch (ParseException e) {
          System.out.println(e);
        JFormattedTextField ftf= new JFormattedTextField(mf1);
        final DefaultTableModel dtm= createTableModel(headers);
        dtm.addRow(new Object[]{new java.util.Date(), "1-23"});
        JTable table= new JTable(dtm);
        DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel
    //  Use custom editors
        dcm.getColumn(0).setCellEditor(new DefaultCellEditor(ftfDate));
    //    dcm.getColumn(0).setCellRenderer(new MyDateRenderer());
        dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
        JScrollPane scrollPane = new JScrollPane(table);
        cp.add(scrollPane, BorderLayout.CENTER);
        setVisible(true);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new FTFTable();
      private DefaultTableModel createTableModel(Object[] columnNames) {
        DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
          public Class getColumnClass(int column) {
         Class returnValue;
         if (column>=0 && column<getColumnCount()) {
           returnValue= getValueAt(0, column).getClass();
         else {
           returnValue= Object.class;
         return returnValue;
        return tblModel;
      class MyDateRenderer extends DefaultTableCellRenderer {
        DateFormat format;
        public MyDateRenderer() {
          super();
          format= new SimpleDateFormat("dd.MM.yyyy");
        public void setValue(Object value) {
          if (value instanceof String) System.out.println("Is String");
          if (value instanceof Object) System.out.println("Is Object");
          System.out.println(value);
          System.out.println(format.format(value)); // Crashes if String
          setText((value == null) ? "" : format.format(value));
    }

    Thanks Rob, that was helpful advice.
    If one needs the date displayed only in the form of one's own locale, there's
    no need to implement a cell renderer. Using a JFormattedTextField provides the
    additional facility of using the arrow keys to modify days, months or year.
    import java.awt.*;
    import java.text.*; // ParseException
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.text.*; // MaskFormatter
    import javax.swing.table.*;
    public class FTFTable extends JFrame {
      public FTFTable() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200, 200);
        setTitle("FTFTable");
        Container cp = getContentPane();
        String headers[] = {"Date", "Mask: #-##"};
        MaskFormatter mf1= null;
        try {
          mf1= new MaskFormatter("#-##");
          mf1.setPlaceholderCharacter('_');
        catch (ParseException e) {
          System.out.println(e);
        JFormattedTextField ftf= new JFormattedTextField(mf1);
        DefaultTableModel dtm= createTableModel(headers);
        dtm.addRow(new Object[]{new Date(), "1-23"});
        JTable table= new JTable(dtm);
    //    Locale.setDefault(Locale.FRANCE);
    //  Use custom editors
        table.setDefaultEditor(Date.class, new DateEditorSupply().getEditor());
        DefaultTableColumnModel dcm=(DefaultTableColumnModel)table.getColumnModel();
        dcm.getColumn(1).setCellEditor(new DefaultCellEditor(ftf));
        JScrollPane scrollPane = new JScrollPane(table);
        cp.add(scrollPane, BorderLayout.CENTER);
        setVisible(true);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new FTFTable();
      private DefaultTableModel createTableModel(Object[] columnNames) {
        DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
          public Class getColumnClass(int column) {
         Class returnValue;
         if (column>=0 && column<getColumnCount()) {
           returnValue= getValueAt(0, column).getClass();
         else {
           returnValue= Object.class;
         return returnValue;
        return tblModel;
      public class DateEditorSupply {
        DateEditor editor;
        SimpleDateFormat format;
        public DateEditorSupply() {
    //     To be modified according to the locale's default.
    //      this("dd MMM yyyy"); // FRANCE
    //      this("dd.MM.yyyy"); // GERMANY
          this("dd-MMM-yyyy"); // UK
    //      this("MMM d, yyyy"); // US
    //Currently this constructor can only be used with the locale's default pattern.
    // If you need various patterns, you have to implement a cell renderer as well.
        public DateEditorSupply(String pattern) {
          format= new SimpleDateFormat(pattern);
          format.setLenient(false);
          editor= new DateEditor();
        public DefaultCellEditor getEditor() {
          return editor;
        private class DateEditor extends DefaultCellEditor {
          public DateEditor() {
         super(new JFormattedTextField(new DateFormatter(format)));
          @Override
          public Object getCellEditorValue() {
         try {
           java.sql.Date value= new java.sql.Date(format.parse(
                   ((JTextField)getComponent()).getText()).getTime());
           return value;
         catch (ParseException ex) {
           return null;
          @Override
          public Component getTableCellEditorComponent(
              final JTable table, final Object value,
              final boolean isSelected, final int row, final int column) {
         JTextField tf= ((JTextField)getComponent());
         tf.setBorder(new LineBorder(Color.black));
         try {
           tf.setText(format.format(value));
         catch (Exception e) {
           tf.setText("");
         return tf;
          public boolean parseDate(String value) {
         ParsePosition pos= new ParsePosition(0);
         format.parse(value, pos); // updates pos.
         if (pos.getIndex()!=value.length() ||
             format.getCalendar().get(Calendar.YEAR)>2500) return false;
         return true;
          @Override
          public boolean stopCellEditing() {
         String value = ((JTextField)getComponent()).getText();
         if (!value.equals("")) {
    /*       This code would accept alphabetic characters within or at the end of
    //       the year in a dd.MM.yyyy pattern, as well as more than 4-digits in the
    //       year string.
           try {
             format.parse(value);
           catch (ParseException e) {
             ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
             return false;
           We avoid this in using "parseDate(value)" instead.
           if (!parseDate(value)) {
             ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
             return false;
         return super.stopCellEditing();
        } // end DateEditor
    }Thanks to André for sharing his .
    Edited by: Joerg22 on 03.07.2010 14:11
    I made some changes to the DateEditorSupply class, so that the code can easily be used when storing the table date in a database.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Currency Format

    Good evening everyone,
    I am working on a banking system and I have a field that needs to be automatically updated with a certain format (i,e: format the currency on-the-fly). I have used two options
    1 - Used a method that returns Document object and validate the field.
    2 - Used the KeyEvent handler (keyReleased()).
    The question is:
    is there a ready class or method for such thing, since I am left with little changes.
    If I continue with my approaches what is the best way?
    thanx in advance

    Java_Madness wrote:
    Good evening everyone,
    I am working on a banking system and I have a field that needs to be automatically updated with a certain format (i,e: format the currency on-the-fly). I have used two options
    1 - Used a method that returns Document object and validate the field.
    2 - Used the KeyEvent handler (keyReleased()).
    The question is:
    is there a ready class or method for such thing, since I am left with little changes.
    If I continue with my approaches what is the best way?A JFormattedTextField with an InputVerifier may be what you want.
    Jim S.

Maybe you are looking for

  • Mobility Radeon 7500 OpenGL issues

    Whenever I attempt to use anything involving openGL, my CPU usage hits 100%. Complex openGL programs will drop to a framerate of less than 10, and sometimes crash Xorg.  How can I fix this? General system info: lspci 00:00.0 Host bridge: Intel Corpor

  • How do I install on new computer?

    I purchased Adobe Creative Cloud (Lightroom and Photoshop) some time ago. I purchased a new computer but see no options to tie into the cloud. In fact, when logged into Adobe, it doesn't seem to recognize I've already purchased this product. Any idea

  • Help with pathfinding program

    hi, i study java at school and i need help with my project. im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points are

  • How can I embed the index of many files at once without cataloging

    As the subject says I need to increase the search speed of thousands of individual PDFs, but not have them cataloged.  When they go on their website our search doesn't search through the catalogue index, it just searches the pdf itself.  So catalogin

  • Deploy Lync 2013 in phases

    Can someone shed some light in this ? I really appreciate. We currently have OCS 2007 (non R2), and planning to upgrade to 2013. We understand the choices of path of migration. However we want to understand if we can deploy 2013 with the the same fea