Formatting tempTextField in Java .

Okay, so here is my latest challenge. I am writing this for school. So far, I have been able to get the GUI to function 'basically' the way I want it to, but I have run into some trouble integrating a Formatted Text Field. What I cannot understand is why the program won't accept 5.75 for an interest rate - it defaults to 5 - when the calculation module worked fine in a different program before I plugged its logic into my GUI program. That being said, I am posting my code, and any input would be helpful. Thanks in advance!

CODE:

import java.text.DecimalFormat;
import java.text.NumberFormat;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MortgageCalculatorGUI.java
 *
 * Created on Dec 18, 2011, 9:01:24 PM
 */
/**
 *
 * @author Roy Kosch
 */
public class MortgageCalculatorGUI extends javax.swing.JFrame {

    /** Creates new form MortgageCalculatorGUI */
    public MortgageCalculatorGUI() {
        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() {

        tempTextField1 = new javax.swing.JTextField();
        tempTextField2 = new javax.swing.JTextField();
        tempTextField3 = new javax.swing.JTextField();
        interestLabel = new javax.swing.JLabel();
        termLabel = new javax.swing.JLabel();
        loanLabel = new javax.swing.JLabel();
        calculateButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();
        paymentLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Kosch Mortgage Calculator");

        tempTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tempTextField1ActionPerformed(evt);
            }
        });

        tempTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tempTextField2ActionPerformed(evt);
            }
        });

        interestLabel.setText("Interest");

        termLabel.setText("Loan Term");

        loanLabel.setText("Loan Amount");

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

        backButton.setText("Go Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        quitButton.setText("QUIT");
        quitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitButtonActionPerformed(evt);
            }
        });

        paymentLabel.setText("Your payment is:");

        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(77, 77, 77)
                        .addComponent(tempTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(interestLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addComponent(quitButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(tempTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tempTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(termLabel)
                            .addComponent(loanLabel)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(66, 66, 66)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(paymentLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(calculateButton)
                                .addGap(18, 18, 18)
                                .addComponent(backButton)))))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {backButton, calculateButton, interestLabel, loanLabel, quitButton, tempTextField1, tempTextField2, tempTextField3, termLabel});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tempTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(interestLabel))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tempTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(termLabel))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tempTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(loanLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(paymentLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(calculateButton)
                    .addComponent(backButton))
                .addGap(18, 18, 18)
                .addComponent(quitButton)
                .addGap(39, 39, 39))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {backButton, calculateButton, interestLabel, loanLabel, quitButton, tempTextField1, tempTextField2, tempTextField3, termLabel});

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

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

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

    private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
        {
        NumberFormat formatter = new DecimalFormat("#0.00");

        double principalLoan = (int)((Double.parseDouble(tempTextField3.getText())));
        double loanInterest = (int)((Double.parseDouble(tempTextField1.getText())));
        double loanTerm = (int)((Double.parseDouble(tempTextField2.getText())));

        double compoundMultiplier = loanInterest/1200;
        double termMultiplier = loanTerm*(12);
        double exponent = -1*(termMultiplier);

        double a = 1+compoundMultiplier;
        double b = Math.pow(a,exponent);
        double c = 1 - b;
        double d = compoundMultiplier/c;

        double mortgagePayment = d*principalLoan;


        paymentLabel.setText("Your Payment is: $" + formatter.format(mortgagePayment));

        }
    }                                               

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

    }                                          

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

    }                                          

    /**
     * @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(MortgageCalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MortgageCalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MortgageCalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MortgageCalculatorGUI.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 MortgageCalculatorGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton backButton;
    private javax.swing.JButton calculateButton;
    private javax.swing.JLabel interestLabel;
    private javax.swing.JLabel loanLabel;
    private javax.swing.JLabel paymentLabel;
    private javax.swing.JButton quitButton;
    private javax.swing.JTextField tempTextField1;
    private javax.swing.JTextField tempTextField2;
    private javax.swing.JTextField tempTextField3;
    private javax.swing.JLabel termLabel;
    // End of variables declaration
}

Answers


Problem : Unnecessary casting to int .

Solution : Don't unnecessarily cast these to int.

    double principalLoan = Double.parseDouble(tempTextField3.getText());
    double loanInterest  = Double.parseDouble(tempTextField1.getText());
    double loanTerm      = Double.parseDouble(tempTextField2.getText());

I can't find a formatted text field in your code. But I find the following line

double loanInterest = (int) ((Double.parseDouble(tempTextField1.getText())));

where you cast your Double into a int. Maybe you mean

double loanInterest = Double.parseDouble(tempTextField1.getText());

I'd suggest to use JFormattedTextField instead of plain JTextField, because derived JFormattedTextField knows NumberFormat.getNumberInstance for example

myFormattedTextField.setMinimumFractionDigits(2);
myFormattedTextField.setMaximumFractionDigits(2);
myFormattedTextField.setRoundingMode(RoundingMode.HALF_UP);

but little bit complicated to set/getValue

  • for set is there myFormattedTextField.setValue()

  • for get is there ((((Number) myFormattedTextField.getValue()).doubleValue()))

don't use depreciated Java Desktop Aplications and its GroupLayout, sometime is so hard to place JComponenets correctly inside Container, use another and proper LayoutManager

don't add ActionListener to the JTextField, use DocumentListener


You cast te parsed double into int, losing the fraction:

double principalLoan = (int)((Double.parseDouble(tempTextField3.getText())));
double loanInterest = (int)((Double.parseDouble(tempTextField1.getText())));
double loanTerm = (int)((Double.parseDouble(tempTextField2.getText())));

Just remove the casting and it should be OK:

double principalLoan = Double.parseDouble(tempTextField3.getText());
double loanInterest = Double.parseDouble(tempTextField1.getText());
double loanTerm = Double.parseDouble(tempTextField2.getText());

Need Your Help

PHP shows “{” or “[” for JSON Object Attributes sent via Angular $http

javascript php json angularjs http-post

I've never seen this problem before, and I can't find the issue anywhere online. I'm using Angular to post form data to a PHP page. I'm using the file_get_contents() method of retrieving the POST d...

PHP Libraries - what are they and how to create one

php c dll libraries

1) Is a PHP library (as in the GD Library) a compiled DLL (or other appropriate name if that is not used outside of Windows) written in a language such as C, compiled, and then "loaded" and made

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.