我的JFormattedTextField
对象上有两个JFrame
对象。我想要这些JFormattedTextField
对象的值的基本数学(加法)。我希望当焦点丢失第一个或第二个文本字段时发生。但是当“focusLost()
”时,事件没有获得最后一个值,而是得到了先前的值。
例如; tf1
首先为0,而tf2
为0。我将2写入tf1
,并且当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);
和
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)));
}
最佳答案
我认为您应该使用PropertyChangeListener
,请参阅How to Write a Property Change Listener。
有一个使用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...
}
}
关于java - FocusEvent没有获取JFormattedTextField的最后一个值,我该如何获取呢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6803976/