2009-12-02 70 views
4

我正在使用下面的代碼片段創建一個JFormattedTextField。通過GUI文本字段輸入值時,格式將按預期工作。但是,當我以編程方式設置值格式不會發生。我如何強制這種情況發生?在JFormattedTextField中設置文本

JFormattedTextField myTextField = new JFormattedTextField(new DecimalFormat("#0.###")); 
// Formatting Does Not Occur 
myTextField.setText("555.55555"); 

回答

5

看看執行setValue()方法

試試這個

myTextField.setValue(new Float("555.55555")); 
4

要添加到OTisler's answer

從Javadoc文檔JFormattedTextField.setText()

請注意,te xt不屬於綁定的 屬性,因此當PropertyChangeEvent發生更改時不會觸發PropertyChangeEvent 。要監聽文本的 更改,請使用 DocumentListener。

從的Javadoc JFormattedTextField.setValue()

設置將通過從 當前AbstractFormatterFactory獲得的AbstractFormatter進行格式化 的值。