FocusEvent没有得到JFormattedTextField的最后一个值,我怎么能得到它?

Yas*_*muş 8 java swing focus jframe jformattedtextfield

我的JFormattedTextField物体上有两个物体JFrame.我希望通过这些JFormattedTextField对象的值得到基本的数学(加法).当焦点丢失第一个或第二个文本字段时,我希望它发生.但是当" focusLost()",事件没有得到最后一个值时,它会得到之前的值.

例如; tf1tf20,最初为0.我写了2 tf1,当when focusLost()(tf1+tf2)变为0时,当我改变其中任何一个时,结果变为2(前一个值)

如何获取focusLost上的最后一个值?

这是我的代码:

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

tf2=new JFormattedTextField(format);
tf2.addFocusListener(this);
Run Code Online (Sandbox Code Playgroud)

并且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)));
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*nas 6

我认为您应该使用a PropertyChangeListener,请参阅如何编写属性更改侦听器.

有一个例子使用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...
    }
}
Run Code Online (Sandbox Code Playgroud)