Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - FocusEvent doesn't get the last value of JFormattedTextField, How I can get it?

I have two JFormattedTextField objects on my JFrame object. I want a basic Math (addition) by the values of these JFormattedTextField objects. I want it happen when focus lost either the first or the second textfield. But when "focusLost()", event doesn't get the last value, it gets the previous value.

For example; tf1 has 0 and tf2 has 0 at first. I write 2 to tf1, and when focusLost(), result (tf1+tf2) become still 0. when I change any of them, the result becomes 2 (the previous value)

How do I get the last values on focusLost?

Here is my code:

JFormattedTextField tf1,tf2;
NumberFormat format=NumberFormat.getNumberInstance();
tf1=new JFormattedTextField(format);
tf1.addFocusListener(this);

tf2=new JFormattedTextField(format);
tf2.addFocusListener(this);

and focusLost():

public void focusLost(FocusEvent e) {
    if(tf1.getValue() == null) tf1.setValue(0); 
    if(tf2.getValue() == null) tf2.setValue(0);
    //because if I dont set, it throws nullPointerException for tf.getValue()

    BigDecimal no1 = new BigDecimal(tf1.getValue().toString());
    BigDecimal no2 = new BigDecimal(tf2.getValue().toString());
    System.out.println("total: " + (no1.add(no2)));
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think you should use a PropertyChangeListener, see How to Write a Property Change Listener.

There is an example using JFormattedTextField:

//...where initialization occurs:
double amount;
JFormattedTextField amountField;
...
amountField.addPropertyChangeListener("value",
                                      new FormattedTextFieldListener());
...
class FormattedTextFieldListener implements PropertyChangeListener {
    public void propertyChanged(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == amountField) {
            amount = ((Number)amountField.getValue()).doubleValue();
            ...
        }
        ...//re-compute payment and update field...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...