?
Solved

Java Help with JComboBox

Posted on 2011-04-22
15
Medium Priority
?
377 Views
Last Modified: 2012-08-13
Trying to add a JComboBox for the user to select the rate and years for mortgage and then calculate the monthly mortgage after the user enters the principal amount and selects item from combo box. Cannot get it to calculate with the code I have and have try different ways.


// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import java.text.DecimalFormat;   //For display the monthly payments as money


// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    //JLabel years_label = null;
    //JTextField years_text = null;

    //JLabel rate_label = null;
    //JTextField rate_text = null;

     JLabel choose_label = null;
     JComboBox choose_combo = null;

    //GUI for the Result Area
    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int number_years; //30 year term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment = 0.00;  // monthly payment for mortgage
        double monthly_interest_rate = interest_rate / 12; // monthly interest
        int number_of_months =  number_years * 12; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 10, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 24));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 55, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 55, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 95, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};

            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 95, 160, 30);
      
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 180, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 180, 90, 30);
            btnCalculate.setText("Calculate");

            // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fields and calculate
            // and add it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the fields
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                  JComboBox cb = (JComboBox)e.getSource();
                
                  
                String str = (String)cb.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }

                 

                 

                   // Sets the result text
                result.setText("Loan Amount = " + money.format(principal)
    		+"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
    		+ Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
    		+ money.format(monthly_payment));//calling the monthly_payment() method of loan class

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());

        }

        return contentPanel;
    }

    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < 360; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        //rate_text.setText("");
        //years_text.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
Comment
Question by:craftyfirst
  • 8
  • 4
  • 3
15 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35449488

Modfy this way:

      //JComboBox cb = (JComboBox)e.getSource();  --thiis comment out


                String str = (String)choose_combo.getSelectedItem();  //here change cb to choos_combo
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35449531
Make the following alteration
//JComboBox cb = (JComboBox) e.getSource();

                        String str = (String) choose_combo.getSelectedItem();

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35449565

You can sometimes use getSource(), say, as a first operator in actionPerformed(ActionEvent e)
in such way:

public void actionPerformed(ActionEvent e){
if(e.getSource().equals(choose_combo)) {

//do something if the action comes from this JComboBox

} else if (e.getSource().equals(some_other_component)) {

// dp somthing with that component
}


}

But in this case you have only one component registered with ActionListener
you don't need to do this check, because
once actionEvent happened you are guaranteed
that it came from this JComboBox
If there could be more componenets registered
with AcrtionListener, then you would have needed getSource()
to understand what was the source of the event


0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 35449588
Of course, you'll need to check the validity of 'str' before proceeding
0
 

Author Comment

by:craftyfirst
ID: 35449990
Thanks that did work, but I forgot a piece of code that I must have deleted when trying to get the button to calculate the mortgage. I have added some code.

When the user enters the amount of loan and selects a mortgage plan it needs to calculate the monthly mortgage


// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import java.text.DecimalFormat;   //For display the monthly payments as money


// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    //JLabel years_label = null;
    //JTextField years_text = null;

    //JLabel rate_label = null;
    //JTextField rate_text = null;

     JLabel choose_label = null;
     JComboBox choose_combo = null;

    //GUI for the Result Area
    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int number_years; //30 year term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment = 0.00;  // monthly payment for mortgage
        double monthly_interest_rate = interest_rate / 12; // monthly interest
        int number_of_months =  number_years * 12; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 10, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 24));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 55, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 55, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 95, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};

            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 95, 160, 30);
      
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 180, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 180, 90, 30);
            btnCalculate.setText("Calculate");

            // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fields and calculate
            // and add it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the fields
                public void actionPerformed(ActionEvent e) {
                  
                principal=Double.parseDouble(principal_text.getText());
                interest_rate=0.0;
                number_years=0;

                String str = (String) choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                        monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }

                 if(e.getSource().equals(choose_combo)) {
                // Calculation for monthly payments on the mortgage
                 monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));
                 
                    }
                   // Sets the result text
                result.setText("Loan Amount = " + money.format(principal)
    		+"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
    		+ Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
    		+ money.format(monthly_payment));//calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());

        }

        return contentPanel;
    }

       


    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < 360; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        //rate_text.setText("");
        //years_text.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35450019
This code does not work
But previous one worked.

let's start wityh the code that worked - what do we want to cghange from there - please explain.

 



0
 
LVL 47

Expert Comment

by:for_yan
ID: 35450080

 I guees this fromula is wrong:
     monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35450165

This works:


// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import java.text.DecimalFormat;   //For display the monthly payments as money


// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    //JLabel years_label = null;
    //JTextField years_text = null;

    //JLabel rate_label = null;
    //JTextField rate_text = null;

     JLabel choose_label = null;
     JComboBox choose_combo = null;

    //GUI for the Result Area
    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int number_years; //30 year term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment = 0.00;  // monthly payment for mortgage
        double monthly_interest_rate = interest_rate / 12; // monthly interest
        int number_of_months =  number_years * 12; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 10, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 24));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 55, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 55, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 95, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};

            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 95, 160, 30);

            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 180, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 180, 90, 30);
            btnCalculate.setText("Calculate");

            // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fields and calculate
            // and add it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the fields
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                 // JComboBox cb = (JComboBox)e.getSource();


                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                        number_of_months = 120;
                        monthly_interest_rate = interest_rate/12.0;

                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                        number_of_months = 240;
                         monthly_interest_rate = interest_rate/12.0;

                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                    number_of_months = 360;
                     monthly_interest_rate = interest_rate/12.0;
                }


           //      monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));

                   monthly_payment = (principal*monthly_interest_rate)/(1-Math.pow(1+monthly_interest_rate, -number_of_months));

                    System.out.println(monthly_payment);


                   // Sets the result text
                result.setText("Loan Amount = " + money.format(principal)
    		+"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
    		+ Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
    		+ monthly_payment); 

                    //money.format(monthly_payment));//calling the monthly_payment() method of loan class

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());

        }

        return contentPanel;
    }

    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < 360; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        //rate_text.setText("");
        //years_text.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35450168
You didn't calculate a bunch of parameters number of months,
monthly interst rate, etc, so the formula was givining infinity
0
 

Author Comment

by:craftyfirst
ID: 35450174
Actually that formula is right because I have used it in my previous assignment when I had three text fields and for this assignment, I needed to take away two text fields and add the combo box.

The action listener will
1. get the principal from the principal_text field that the user inputs
2. then the user will select the mortgage plan from the combo box
3. once the user clicks on the calculate button it should calculate the monthly mortgage

this is what I added after the if else statements for the arrays

  if(e.getSource().equals(choose_combo)) {
                // Calculation for monthly payments on the mortgage
                 monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));

If I did not put the if statement for the calculations it just gives me black diamonds in the fields that need to be calculate. Once I put the if statement above the calculation it at least puts zeros in the fields. Is there another piece of code I need to add?
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35450179
This looks a little bit nicer - you don't want to calculate monthly rate in therr different places


// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import java.text.DecimalFormat;   //For display the monthly payments as money


// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    //JLabel years_label = null;
    //JTextField years_text = null;

    //JLabel rate_label = null;
    //JTextField rate_text = null;

     JLabel choose_label = null;
     JComboBox choose_combo = null;

    //GUI for the Result Area
    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int number_years; //30 year term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment = 0.00;  // monthly payment for mortgage
        double monthly_interest_rate = interest_rate / 12; // monthly interest
        int number_of_months =  number_years * 12; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 10, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 24));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 55, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 55, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 95, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};

            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 95, 160, 30);

            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 180, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 180, 90, 30);
            btnCalculate.setText("Calculate");

            // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fields and calculate
            // and add it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the fields
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                 // JComboBox cb = (JComboBox)e.getSource();


                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                        number_of_months = 120;
                 

                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                        number_of_months = 240;


                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                    number_of_months = 360;

                }


           //      monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));

                     monthly_interest_rate = interest_rate/12.0;

                   monthly_payment = (principal*monthly_interest_rate)/(1-Math.pow(1+monthly_interest_rate, -number_of_months));

                    System.out.println(monthly_payment);


                   // Sets the result text
                result.setText("Loan Amount = " + money.format(principal)
    		+"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
    		+ Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
    		+ monthly_payment); 

                    //money.format(monthly_payment));//calling the monthly_payment() method of loan class

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());

        }

        return contentPanel;
    }

    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < 360; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        //rate_text.setText("");
        //years_text.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
 

Author Comment

by:craftyfirst
ID: 35450209
Yes, this work. Thank you.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35450211
Yes, the formula was right, but it uses number_of_months and monthly_interest_rate,
and you did not calcllate them from number of years and annual inters rate
therefore these parameters were zero, as it was dividing by zero it was ggetting inelgibilbe
numbers

I added number_of_months and calculated monthly_interest_rates
and it started working.

maybwe you alsio want to calculate number of months as
number_of_year*12,
I just put in every brace the number,
but for your teacher better to calculete
it once:

OK, this is final:

Don't break it!

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import java.text.DecimalFormat;   //For display the monthly payments as money


// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    //JLabel years_label = null;
    //JTextField years_text = null;

    //JLabel rate_label = null;
    //JTextField rate_text = null;

     JLabel choose_label = null;
     JComboBox choose_combo = null;

    //GUI for the Result Area
    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int number_years; //30 year term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment = 0.00;  // monthly payment for mortgage
        double monthly_interest_rate = interest_rate / 12; // monthly interest
        int number_of_months =  number_years * 12; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 10, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 24));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 55, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 55, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 95, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 12));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};

            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 95, 160, 30);

            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 180, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 180, 90, 30);
            btnCalculate.setText("Calculate");

            // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fields and calculate
            // and add it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the fields
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                 // JComboBox cb = (JComboBox)e.getSource();


                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                       
                 

                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;


                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;


                }


           //      monthly_payment = principal * (monthly_interest_rate / (1 - Math.pow((1 + monthly_interest_rate),-number_of_months)));

                     monthly_interest_rate = interest_rate/12.0;
                     number_of_months = number_years*12;

                   monthly_payment = (principal*monthly_interest_rate)/(1-Math.pow(1+monthly_interest_rate, -number_of_months));

                    System.out.println(monthly_payment);


                   // Sets the result text
                result.setText("Loan Amount = " + money.format(principal)
    		+"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
    		+ Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
    		+ monthly_payment); 

                    //money.format(monthly_payment));//calling the monthly_payment() method of loan class

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());

        }

        return contentPanel;
    }

    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < 360; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        //rate_text.setText("");
        //years_text.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window


0
 

Author Comment

by:craftyfirst
ID: 35450253
thanks

I will not touch it.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35453569
Glad i solved the problem ;)
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month8 days, 19 hours left to enroll

621 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