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

前端 未结 2 1779
一个人的身影
一个人的身影 2020-12-02 00:55

I have a jFormattedTextField and I set setCommitsOnValidEdit to true then I added an event listener to \"property change\" on \"value\" property.

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 01:23

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

提交回复
热议问题