我正在使用swing用gui写一个简单的贷款计算器。我使用DecimalFormat来确保以JFormattedTextField的指定格式####。##捕获输入。
public static void main(String[] args) {
JFormattedTextField loanAmountField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField interestRateField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField yearField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField monthlyPaymentField = new JFormattedTextField(new DecimalFormat("####.##"));
}
当用户按下我的“计算”按钮时,它将计算并显示monthlyPaymentField。
为了测试程序是否可以正确显示,我尝试为monthlyPaymentField分配值12.22,但是却收到一条错误消息,提示monthlyPaymentField应该声明为double。
class CalculateListener implements ActionListener {
public CalculateListener (JFormattedTextField loanAmountField, JFormattedTextField monthlyPaymentField, JFormattedTextField interestRateField, JFormattedTextField yearField, int monthlyTest)
{
this.interestRateField = interestRateField;
this.yearField = yearField;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
this.monthlyTest = monthlyTest;
}
public void actionPerformed(ActionEvent event){
monthlyPaymentField = 12.22;
}
}
我该怎么做,以便我仍然可以将JFormattedTextField与DecimalFormat一起使用,但仍可以在我的monthlyPaymentField上显示Float?
最佳答案
您可以使用setValue
方法。
monthlyPaymentField.setValue(new Double(12.22));