【问题标题】:Assigning JFormattedTextField a Float为 JFormattedTextField 分配一个浮点数
【发布时间】:2012-06-21 23:34:13
【问题描述】:

我正在使用 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 上显示一个浮点数?

【问题讨论】:

    标签: java swing jformattedtextfield


    【解决方案1】:

    您可以为此使用setValue 方法;

    monthlyPaymentField.setValue(new Double(12.22)); 
    

    【讨论】:

    • @Max 你们知道为什么它没有在我的(摆动)GUI 上显示新值吗?
    【解决方案2】:

    使用setValue,即:

    monthlyPaymentField.setValue(new Double(12.22));
    

    How to Use Formatted Text Fields 教程有一个很好的双打示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2014-04-06
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多