为什么ActionEvent返回0而不是从公式计算未来的复合利息?

时间:2015-07-22 01:31:35

标签: java swing netbeans

我正在尝试在NetBeans中创建的JFrame中创建一个简单的未来复合兴趣应用程序。用户将在JFrame中的每个JTextField中键入当前金额,季度费率和年数。当用户点击'计算'按下resultTextField应该打印结果。但是,无论输入的数字是什么,我的程序都会返回0。

我猜这段代码中缺少一些东西:

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt)    {
    if(evt.getSource().equals(calculateButton))
{
   result =  compoundMethod(int1, int2, int3);
   resultTextField.setText(String.valueOf(result));

}
}

我不确定这里的问题是什么。有人可以帮我吗。非常感谢它。谢谢!

package apppackage; //Declared in netbeans

public class interestGUI extends javax.swing.JFrame {

public double int1 = 0;
public double int2 = 0;
public double int3 = 0;
public double result = 0;
/**
 * Creates new form interestGUI
 */
public interestGUI() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    amountTextField = new javax.swing.JTextField();
    rateTextField = new javax.swing.JTextField();
    periodsTextField = new javax.swing.JTextField();
    AmountLabel = new javax.swing.JLabel();
    RateLabel = new javax.swing.JLabel();
    PeriodsLabel = new javax.swing.JLabel();
    FormulaTextField = new javax.swing.JTextField();
    resultTextField = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    calculateButton = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    amountTextField.setText("0");
    amountTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            amountTextFieldActionPerformed(evt);
        }
    });

    rateTextField.setText("0");
    rateTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            rateTextFieldActionPerformed(evt);
        }
    });

    periodsTextField.setText("0");
    periodsTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            periodsTextFieldActionPerformed(evt);
        }
    });

    AmountLabel.setText("Amount");

    RateLabel.setText("Rate");

    PeriodsLabel.setText("Periods");

    FormulaTextField.setText("S = P ( 1 + i * t) ");
    FormulaTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            FormulaTextFieldActionPerformed(evt);
        }
    });

    resultTextField.setText("0");
    resultTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            resultTextFieldActionPerformed(evt);
        }
    });

    jLabel1.setText("Future Value Formula");

    calculateButton.setText("Calculate");
    calculateButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            calculateButtonActionPerformed(evt);
        }
    });

    jLabel2.setText("Result:");

    javax.swing.GroupLayout layout = new        javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(172, 172, 172)
                    .addComponent(calculateButton))
                .addGroup(layout.createSequentialGroup()
                    .addGap(94, 94, 94)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(17, 17, 17)
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(resultTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(AmountLabel)
                                .addComponent(amountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(50, 50, 50)
                                    .addComponent(RateLabel)
                                    .addGap(54, 54, 54))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(rateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(37, 37, 37)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(PeriodsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(periodsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGroup(layout.createSequentialGroup()
                    .addGap(154, 154, 154)
                    .addComponent(FormulaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(143, 143, 143)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(128, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(4, 4, 4)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(FormulaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(AmountLabel)
                .addComponent(RateLabel)
                .addComponent(PeriodsLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(amountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(rateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(periodsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(calculateButton)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(resultTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addGap(26, 26, 26))
    );

    pack();
}// </editor-fold>



 public double compoundMethod(double presentValue, 
         double interestRate, double totalInterestPeriods )
  {
double compoundBalance;
totalInterestPeriods = totalInterestPeriods*4;
interestRate = ((interestRate/100) / 4); // Compute interestRate (updated)
compoundBalance = presentValue*(Math.pow(1+interestRate,      totalInterestPeriods));


return compoundBalance;

 }



private void amountTextFieldActionPerformed(java.awt.event.ActionEvent evt)     {
int1 = Double.parseDouble(amountTextField.getText());
}

private void rateTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
int2 =  Double.parseDouble(rateTextField.getText());
}

private void periodsTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
int3 = Double.parseDouble(periodsTextField.getText());
}

private void FormulaTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if(evt.getSource().equals(calculateButton))
{
   result =  compoundMethod(int1, int2, int3);
   resultTextField.setText(String.valueOf(result));

}
}

private void resultTextFieldActionPerformed(java.awt.event.ActionEvent evt)    {
  resultTextField.setText(String.valueOf(result));
 }

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(interestGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(interestGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(interestGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(interestGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new interestGUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JLabel AmountLabel;
private javax.swing.JTextField FormulaTextField;
private javax.swing.JLabel PeriodsLabel;
private javax.swing.JLabel RateLabel;
private javax.swing.JTextField amountTextField;
private javax.swing.JButton calculateButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField periodsTextField;
private javax.swing.JTextField rateTextField;
private javax.swing.JTextField resultTextField;
// End of variables declaration
}

1 个答案:

答案 0 :(得分:4)

您的基本问题归结为对ActionEvent生成JTextField的方式的误解。

基本上,当用户按下 Enter 键时(通常)会生成它们。这意味着,如果您在字段具有焦点时从不按 Enter ,则值int1int2int30

相反,当用户按下 Calculate 按钮时,从字段中获取值

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if (evt.getSource().equals(calculateButton)) {
        int1 = Double.parseDouble(amountTextField.getText());
        int2 = Double.parseDouble(rateTextField.getText());
        int3 = Double.parseDouble(periodsTextField.getText());
        result = compoundMethod(int1, int2, int3);
        resultTextField.setText(String.valueOf(result));

    }
}

我还建议您查看使用JSpinnerJFormattedTextField哪些能够比JTextField更好地管理数值

有关详细信息,请查看How to Use Text FieldsHow to Write an Action ListenersHow to Use SpinnersHow to Use Formatted Text Fields