为 JFormattedTextField 分配一个浮点型



我正在使用 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分配一个值12.22,但是我收到一个错误,说monthlyPaymentField应该声明为双精度。

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;
    }
}

该如何做到这一点,以便我仍然可以使用带有DecimalFormat的JFormattedTextField,但仍然可以在我的monthlyPaymentField上显示浮点数?

您可以使用 setValue 方法;

monthlyPaymentField.setValue(new Double(12.22)); 

使用 setValue,即:

monthlyPaymentField.setValue(new Double(12.22));

如何使用格式化文本字段教程有一个很好的双精度示例。

最新更新