我在我的JFrame
對象上有兩個JFormattedTextField
對象。我想通過這些JFormattedTextField
對象的值來獲得基本的數學(加法)。當焦點丟失第一個或第二個文本字段時,我希望它發生。但是當「focusLost()
」,事件沒有得到最後一個值時,它會得到以前的值。FocusEvent未獲取JFormattedTextField的最後一個值,我如何獲取它?
例如; 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)));
}
好主線,有三個可能的聽衆屬性,文檔和焦點+1 – mKorbel
+1我認爲這是更好的方法。 – trashgod