Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Mortgage calculator with GUI- Clear button not working

Posted on 2006-07-21
9
462 Views
Last Modified: 2013-11-23
This is a mortgage calculator with GUI. The clear button is supposed top clear all fields so that the user can start over. Please help, I get errors when I click on the clear button.

import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.io.*;
   import java.text.DecimalFormat;
   import javax.swing.JTextField.*;

   import java.text.NumberFormat;

    public class MortgagePay extends JFrame implements ActionListener
   {
         private static String default_loan = null;
         private static String default_term = null;
         private static String default_rate = null;
         private static String default_payment = null;



      //setup format for currency
          DecimalFormat money = new DecimalFormat("$###,###.00");


          //Declare output stream
          DataOutputStream output;

          //Construct a panel for each row
          private JPanel firstRow = new JPanel();
          private JPanel secondRow = new JPanel();
          private JPanel thirdRow = new JPanel();
          private JPanel fourthRow = new JPanel();

          //Construct a panel for the fields and buttons
          JPanel fieldPanel = new JPanel();
          JPanel buttonPanel = new JPanel();

          private JTextField loanField;
          private JTextField termField;
          private JTextField rateField;
          private JTextField paymentField;

          //Construct labels and text boxes
          private JLabel loanLabel = new JLabel("Mortgage Amount:          ");
          private JTextField p  = new JTextField(15);
          private JLabel termLabel = new JLabel("Term (in years):");
          private JTextField t = new JTextField(5);
          private JLabel rateLabel = new JLabel("Interest Rate:");
          private JTextField r = new JTextField(5);
          private JLabel paymentLabel = new JLabel("Payment:");
          private JTextField m = new JTextField(15);
          private JLabel displayPayment = new JLabel();

          //Construct Buttons
          private JButton calculateButton = new JButton("Calculate Payment");
          private JButton clearButton = new JButton("Clear");
          private JButton quitButton = new JButton ("Quit");


       public static void main(String[] args)
      {

      //Set look and feel for the interface
         try
         {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
         }

         catch (Exception e)
         {


            }
         MortgagePay f = new MortgagePay();

         f.setSize(450,350);
         f.setTitle("Mortgage Payment Calculator");
         f.setResizable(false);
         f.setLocation(200,200);
         f.setVisible(true);
      }

       public MortgagePay()
      {
          //Bulid Container
          Container c = getContentPane();
              c.setLayout((new BorderLayout()));
          fieldPanel.setLayout(new GridLayout(8,1));
          FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
               firstRow.setLayout(rowSetup);
               secondRow.setLayout(rowSetup);
               thirdRow.setLayout(rowSetup);
               fourthRow.setLayout(rowSetup);

          buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
          buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));



          //add fields to rows
          firstRow.add(loanLabel);
          firstRow.add(p);
          secondRow.add(termLabel);
          secondRow.add(t);
          thirdRow.add(rateLabel);
          thirdRow.add(r);
          fourthRow.add(paymentLabel);
          fourthRow.add(m);
          fourthRow.add(displayPayment);

          //Add rows to panel
          fieldPanel.add(firstRow);
          fieldPanel.add(secondRow);
          fieldPanel.add(thirdRow);
          fieldPanel.add(fourthRow);
          //add button to panel
          buttonPanel.add(calculateButton);
          buttonPanel.add(clearButton);
          buttonPanel.add(quitButton);

          //Add panels to frame
          c.add(fieldPanel, BorderLayout.CENTER);
          c.add(buttonPanel, BorderLayout.SOUTH);

          //add fuctionality to the button
          calculateButton.addActionListener(this);
          clearButton.addActionListener(this);
          quitButton.addActionListener(this);

     }

       public void actionPerformed(ActionEvent e)
      {
              Object source = e.getSource();


               if(source == clearButton)
                  {
                  loanField.setText(null);
                  termField.setText(null);
                  rateField.setText(null);
                  paymentField.setText(null);

                  }
               if(source == quitButton)
               {
                     System.exit(0);
               }


               //This is going to call the method for doing the math
               mortCal();

       }

                 public void mortCal()
               {
               double principle = Double.parseDouble(p.getText());
               double rate = Double.parseDouble(r.getText());
               double term = Double.parseDouble(t.getText());
               double interest = (rate/100/12);
               double payment = (principle*interest)/(1-Math.pow(1/(1+interest), term*12));
               String displayPayment = (money.format(payment));
               paymentLabel.setText("" + "$" + payment);
               }
   }
0
Comment
Question by:jjbraxton
  • 5
  • 3
9 Comments
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17158816
You are not initialzing "loanField" variable.
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17158822
>                loanField.setText(null);
>                termField.setText(null);
>                rateField.setText(null);
>                paymentField.setText(null);
try changing this to:

            p.setText(null);
            t.setText(null);
            r.setText(null);
            m.setText(null);
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17158829
the function mortCal() should also be changed as:


    public void mortCal() {
        if (p.getText().trim().length() == 0 || r.getText().trim().length() == 0 || t.getText().trim().length() == 0) {
            paymentLabel.setText("Payment:");
            return;
        }

        double principle = Double.parseDouble(p.getText());
        double rate = Double.parseDouble(r.getText());
        double term = Double.parseDouble(t.getText());
        double interest = (rate / 100 / 12);
        double payment = (principle * interest) / (1 - Math.pow(1 / (1 + interest), term * 12));
        displayPayment.setText("" + NumberFormat.getCurrencyInstance(Locale.US).format(payment));
    }
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17158832
In my last comment,
> paymentLabel.setText("Payment:");
should be:
displayPayment.setText(null);
0
 
LVL 10

Assisted Solution

by:mukundha_expert
mukundha_expert earned 100 total points
ID: 17158928
jjbraxton ,

1.
as Ajay-Singh said change,

>                loanField.setText(null);
>                termField.setText(null);
>                rateField.setText(null);
>                paymentField.setText(null);
try changing this to:

            p.setText(null);
            t.setText(null);
            r.setText(null);
            m.setText(null);

2.
Change you actionPerformed() method ( jus a small modification to yours)
      public void actionPerformed(ActionEvent e)
     {
            Object source = e.getSource();


             if(source == clearButton)
               {
//               loanField.setText(null);
//               termField.setText(null);
//               rateField.setText(null);
//               paymentField.setText(null);
                  
                 p.setText(null);
                 t.setText(null);
                 r.setText(null);
                 m.setText(null);

               }
             if(source == quitButton)
             {
                  System.exit(0);
             }

           // Note the chnage
             if ( source == calculateButton )
             //This is going to call the method for doing the math
               mortCal();

       }

3.
The mortcal() need no te changed except the payment shoould be displayed in the textbox .. not in the label

               public void mortCal()
               {
               double principle = Double.parseDouble(p.getText());
               double rate = Double.parseDouble(r.getText());
               double term = Double.parseDouble(t.getText());
               double interest = (rate/100/12);
               double payment = (principle*interest)/(1-Math.pow(1/(1+interest), term*12));
               String displayPayment = (money.format(payment));
                ///Note the change
               m.setText("" + "$" + payment);
               }
   }



BTW,

what will happen if the user enters some characters instead of Numbers, try to check the exceptions in the mortcalc() METHOD
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17158930
>>The mortcal() need no te changed
mortcalc() need not be changed
0
 

Author Comment

by:jjbraxton
ID: 17158933
Thanks. It compiled without errors, but now the Calculate button is not working. This the program with your suggested changes.

import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.io.*;
   import java.text.DecimalFormat;
   import javax.swing.JTextField.*;

   import java.text.NumberFormat;

    public class MortgagePay extends JFrame implements ActionListener
   {
         private static String default_loan = null;
         private static String default_term = null;
         private static String default_rate = null;
         private static String default_payment = null;



      //setup format for currency
          DecimalFormat money = new DecimalFormat("$###,###.00");


          //Declare output stream
          DataOutputStream output;

          //Construct a panel for each row
          private JPanel firstRow = new JPanel();
          private JPanel secondRow = new JPanel();
          private JPanel thirdRow = new JPanel();
          private JPanel fourthRow = new JPanel();

          //Construct a panel for the fields and buttons
          JPanel fieldPanel = new JPanel();
          JPanel buttonPanel = new JPanel();

          private JTextField loanField;
          private JTextField termField;
          private JTextField rateField;
          private JTextField paymentField;

          //Construct labels and text boxes
          private JLabel loanLabel = new JLabel("Mortgage Amount:          ");
          private JTextField p  = new JTextField(15);
          private JLabel termLabel = new JLabel("Term (in years):");
          private JTextField t = new JTextField(5);
          private JLabel rateLabel = new JLabel("Interest Rate:");
          private JTextField r = new JTextField(5);
          private JLabel paymentLabel = new JLabel("Payment:");
          private JTextField m = new JTextField(15);
          private JLabel displayPayment = new JLabel();

          //Construct Buttons
          private JButton calculateButton = new JButton("Calculate Payment");
          private JButton clearButton = new JButton("Clear");
          private JButton quitButton = new JButton ("Quit");


       public static void main(String[] args)
      {

      //Set look and feel for the interface
         try
         {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
         }

         catch (Exception e)
         {


            }
         MortgagePay f = new MortgagePay();

         f.setSize(450,350);
         f.setTitle("Mortgage Payment Calculator");
         f.setResizable(false);
         f.setLocation(200,200);
         f.setVisible(true);
      }

       public MortgagePay()
      {
          //Bulid Container
          Container c = getContentPane();
              c.setLayout((new BorderLayout()));
          fieldPanel.setLayout(new GridLayout(8,1));
          FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
               firstRow.setLayout(rowSetup);
               secondRow.setLayout(rowSetup);
               thirdRow.setLayout(rowSetup);
               fourthRow.setLayout(rowSetup);

          buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
          buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));



          //add fields to rows
          firstRow.add(loanLabel);
          firstRow.add(p);
          secondRow.add(termLabel);
          secondRow.add(t);
          thirdRow.add(rateLabel);
          thirdRow.add(r);
          fourthRow.add(paymentLabel);
          fourthRow.add(m);
          fourthRow.add(displayPayment);

          //Add rows to panel
          fieldPanel.add(firstRow);
          fieldPanel.add(secondRow);
          fieldPanel.add(thirdRow);
          fieldPanel.add(fourthRow);
          //add button to panel
          buttonPanel.add(calculateButton);
          buttonPanel.add(clearButton);
          buttonPanel.add(quitButton);

          //Add panels to frame
          c.add(fieldPanel, BorderLayout.CENTER);
          c.add(buttonPanel, BorderLayout.SOUTH);

          //add fuctionality to the button
          calculateButton.addActionListener(this);
          clearButton.addActionListener(this);
          quitButton.addActionListener(this);

     }

       public void actionPerformed(ActionEvent e)
      {
              Object source = e.getSource();


               if(source == clearButton)
                  {
                  p.setText(null);
                  t.setText(null);
                  r.setText(null);
                  m.setText(null);

                  }
               if(source == quitButton)
               {
                     System.exit(0);
               }


               //This is going to call the method for doing the math
               mortCal();


       }

        public void mortCal()
        {
      {
            if(p.getText().trim().length()==0||r.getText().trim().length()==0||t.getText().trim().length()==0)
            {
                  displayPayment.setText(null);
                  return;
            }


               double principle = Double.parseDouble(p.getText());
               double rate = Double.parseDouble(r.getText());
               double term = Double.parseDouble(t.getText());
               double interest = (rate/100/12);
               double payment = (principle*interest)/(1-Math.pow(1/(1+interest), term*12));
               displayPayment.setText("" + NumberFormat.getCurrencyInstance().format(payment));
               displayPayment.setText(null);
               }
               }
   }
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17158953
have you tried mine??

its working
0
 
LVL 23

Accepted Solution

by:
Ajay-Singh earned 400 total points
ID: 17158961
>                double principle = Double.parseDouble(p.getText());
>                double rate = Double.parseDouble(r.getText());
>                double term = Double.parseDouble(t.getText());
>                double interest = (rate/100/12);
>                double payment = (principle*interest)/(1-Math.pow(1/(1+in<wbr/>terest),
> term*12));
>                displayPayment.setText("" +
> NumberFormat.getCurrencyInstance().forma<wbr/>t(payment)<wbr/>);
>                displayPayment.setText(null);


remove last line "displayPayment.setText(null);"
from this function
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java exception bubble up 2 21
how to install java on RHEL image on EC2 4 41
Java string replace 11 54
Eclipse for Java EE development 2 27
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question