问题描述
我的 JFrame
对象上有两个 JFormattedTextField
对象.我想要这些 JFormattedTextField
对象的值的基本数学(加法).我希望它在焦点丢失第一个或第二个文本字段时发生.但是当focusLost()
"时,事件并没有得到最后一个值,而是得到了前一个值.
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.
例如;tf1
有 0,而 tf2
有 0.我将 2 写入 tf1
,当 focusLost()
时,结果 (tf1+tf2
) 仍然为 0.当我更改其中任何一个时,结果变成2(之前的值)
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)
如何获取 focusLost 上的最后一个值?
How do I get the last values on 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
,参见 如何编写属性更改监听器.
I think you should use a PropertyChangeListener
, see 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...
}
}
这篇关于FocusEvent 没有得到 JFormattedTextField 的最后一个值,我怎样才能得到它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!