jFormattedTextField’s Formatter.setCommitsOnValidEdit(true) doesn’t work at first focus

Actually, setCommitOnValidEdit should work always as you expect (and does in the code snippet below), no need for a DocumentListener, after all, the method is exactly for that purpose. So I suspect something else is wrong in your context. Or for some reason the very first edit isn’t parsed to anything valid?

    NumberFormatter numberFormatter = new NumberFormatter( 
            NumberFormat.getIntegerInstance());
    // allow or not doesn't make a difference
    numberFormatter.setAllowsInvalid(false);  
    numberFormatter.setCommitsOnValidEdit(true);
    JFormattedTextField readTimeOut = new JFormattedTextField(numberFormatter);
    PropertyChangeListener l = new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            LOG.info("got new value: " + evt.getNewValue());
        }
    };
    readTimeOut.addPropertyChangeListener("value", l);
    readTimeOut.setColumns(20);
    readTimeOut.setHorizontalAlignment(SwingConstants.RIGHT);    

    JFormattedTextField other = new JFormattedTextField(numberFormatter);
    other.addPropertyChangeListener("value", l);
    other.setColumns(20);
    other.setHorizontalAlignment(SwingConstants.RIGHT);    
    JPanel box = new JPanel();
    box.add(readTimeOut);
    box.add(other);

Leave a Comment