Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

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

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

At first focus of that jFormattedTextField it doesn't call event listener method when typing in it. But on "focusLost" it calls event listener and after that when it receives focus again it calls event listener when typing.

I want the event listener be called after any change in any time in that jFormattedTextField (Even in the fist focus).

What's the problem? How can I fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...