• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 467
  • Last Modified:

GUI Mortgage Calculator Part 2

Good Evening,

I have redone my code and figured out how to get the text boxes in with the drop down combo_box.  I can calculate the combo_box with the principle amount but my brain is fried on how to get the text fields for interest and years to calculate when I don't choose an item from the drop down box.

here is the code:
/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4
Professor Matt Berg
May 2, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

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.JRadioButton;
import javax.swing.ButtonGroup;
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

public class GutierrezMortgageGui extends JFrame {

	static  String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
   static  String [] toReplace;
         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, scroll 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;	
    		JRadioButton rbutton01 = null;
    		JRadioButton rbutton02 = null;
    		ButtonGroup buttongroup = null;

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

    //GUI for Table with scroll pane    
	 		
    		JScrollPane scrolling_table = null;    		

    // Creates the button for calculation of the mortgage payments
 
    		JButton btnCalculate = null;
    
	 // Creates a button for reset button
   
			JButton btnReset = null;
	 
	 //Variables
	 		
			int numberOfLinesGenerated=1;
        	int number_years; //Term of the mortgage
        	double principal; // Total amount borrowed
        	double interest_rate;  //  Interest rate for mortgage
        	double monthly_payment;  // Monthly payment amount for mortgage
        	double monthly_interest_rate ; // Monthly interest rate
        	int number_of_months; // 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 GutierrezMortgageGui() {
        	super();
        	initialize();
    }

	 //Window size, JPanel, setTitle	
	
    	public void initialize() {
			this.setSize(700,500);
        	this.setContentPane(getJPanel());
        	this.setTitle("Gutierrez Mortgage GUI");
    }

    	public JPanel getJPanel() {
        	if (contentPanel == null) {
            contentPanel = new JPanel();
            contentPanel.setLayout(null);
            contentPanel.setBackground(Color.black);

            // GUI elements to display labels and fields for current information
				// to include Alignment, Boundary, Title, Font, Font Size, Color

            // Main Title of the Calculator
            main_title = new JLabel();
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            main_title.setBounds(130, 20, 400, 30);
            main_title.setText("My First GUI Loan Calculator");
            main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
            main_title.setForeground(Color.white);
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            principal_label.setBounds(90, 65, 220, 25);
            principal_label.setText("Mortgage Principle Amount : ");
            principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            principal_label.setForeground(Color.white);
            contentPanel.add(principal_label);

            //Principal Text Field Features
				          
			   principal_text = new JTextField();
            principal_text.setBounds(350, 65, 160, 25);
            principal_text.setText(Double.toString(principal));
            contentPanel.add(principal_text);
                  
			 				            				
				//Mortgage Plan Label
				
				choose_label = new JLabel();
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            choose_label.setBounds(90, 125, 220, 25);
            choose_label.setText("Select Mortgage Plan : ");
            choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            choose_label.setForeground(Color.white);
            contentPanel.add(choose_label);             

				//String for Mortgage Variation
				
            String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
				contentPanel.add(choose_combo);
				
				// Number of Years Label
			   years_label = new JLabel();
			   years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   years_label.setBounds(90, 200, 220, 25);
			   years_label.setText("Mortgage Term : ");
			   years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   years_label.setForeground(Color.white);
			   contentPanel.add(years_label);

			   // Number of Years Text Field
			   years_text = new JTextField();
			   years_text.setBounds(350, 205, 160, 25);
			   years_text.setText(Double.toString(number_years));
			   contentPanel.add(years_text);

			   // Annual Interest Rate Label
			   rate_label = new JLabel();
			   rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   rate_label.setBounds(90, 165, 220, 25);
			   rate_label.setText("Annunal Interest Rate : ");
			   rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   rate_label.setForeground(Color.white);
			   contentPanel.add(rate_label);

			   // Annual Interest Rate Text Field
			   rate_text = new JTextField();
			   rate_text.setBounds(350, 165, 160, 25);
			   rate_text.setText(Double.toString(interest_rate * 100) + "%");
			   contentPanel.add(rate_text);

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


            // Button for reset button
				
            btnReset = new JButton ();
            btnReset.setBounds(355, 350, 110, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Button for calculation of the mortgage payments
				
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 350,110, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


            // Action listener to the reset button
				
            btnReset.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                onButtonReset();
                 }
            });

     			//Button Press Calculate      
			  
            btnCalculate.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                   
						 
						  //Calculates the number of months for mortgage so as to determine the number of payments to be made
                    number_of_months = number_years * 12;

                    //Calulates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Equation that calculates the monthly payment for 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
						  

                    
                    }

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

            
        }

        return contentPanel;
    }




     
   
    public double getDouble(String val) {
        double value = 00;
        try {
            // This tests to see if there is a dollar sign
            if (val.indexOf('$') > -1) {
                
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            
				// Generates an error here
				
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

   
    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(){    
           principal_text.setText("");
           result.setText("");
           

    }

				
public static void main(String[] args) {

                SwingUtilities.invokeLater(new Runnable() {

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

    

   }

Open in new window

0
PapaDragonX
Asked:
PapaDragonX
  • 5
  • 5
  • 4
2 Solutions
 
for_yanCommented:
Well, you just say
textField.getText() - this returns String
which you wil need to parse

double interest= Double.parseDouble(textField.getText());
0
 
for_yanCommented:
Instead of this:  
principal=getDouble(principal_text.getText());

should be

principal=Double.parseDouble(principal_text.getText());
0
 
objectsCommented:
double rate = Double.parseDouble(rate_text.getText());
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
for_yanCommented:
Well, if you have such method, it may be OK
0
 
PapaDragonXAuthor Commented:
objects: I tried yours "double rate" and it was not able to work.

for yan: yours produces the same results and does not work either.  

both: I still can only use the drop down combo_box

perhaps I need to add another parse?
0
 
objectsCommented:
you can use getDouble() actually, your problem is you override whats in the text field with what selected in your combo.
0
 
PapaDragonXAuthor Commented:
I understand, but I just can't get it to work. I need to override the combo like you said.
0
 
for_yanCommented:

This somehow works:

/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4
Professor Matt Berg
May 2, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

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.JRadioButton;
import javax.swing.ButtonGroup;
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

public class GutierrezMortgageGui extends JFrame {

	static  String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
   static  String [] toReplace;
         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, scroll 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;
    		JRadioButton rbutton01 = null;
    		JRadioButton rbutton02 = null;
    		ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane

	 		JTextArea result = null;
    		JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane

    		JScrollPane scrolling_table = null;

    // Creates the button for calculation of the mortgage payments

    		JButton btnCalculate = null;

	 // Creates a button for reset button

			JButton btnReset = null;

	 //Variables

			int numberOfLinesGenerated=1;
        	int number_years; //Term of the mortgage
        	double principal; // Total amount borrowed
        	double interest_rate;  //  Interest rate for mortgage
        	double monthly_payment;  // Monthly payment amount for mortgage
        	double monthly_interest_rate ; // Monthly interest rate
        	int number_of_months; // 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 GutierrezMortgageGui() {
        	super();
        	initialize();
    }

	 //Window size, JPanel, setTitle

    	public void initialize() {
			this.setSize(700,500);
        	this.setContentPane(getJPanel());
        	this.setTitle("Gutierrez Mortgage GUI");
    }

    	public JPanel getJPanel() {
        	if (contentPanel == null) {
            contentPanel = new JPanel();
            contentPanel.setLayout(null);
            contentPanel.setBackground(Color.black);

            // GUI elements to display labels and fields for current information
				// to include Alignment, Boundary, Title, Font, Font Size, Color

            // Main Title of the Calculator
            main_title = new JLabel();
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            main_title.setBounds(130, 20, 400, 30);
            main_title.setText("My First GUI Loan Calculator");
            main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
            main_title.setForeground(Color.white);
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            principal_label.setBounds(90, 65, 220, 25);
            principal_label.setText("Mortgage Principle Amount : ");
            principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            principal_label.setForeground(Color.white);
            contentPanel.add(principal_label);

            //Principal Text Field Features

			   principal_text = new JTextField();
            principal_text.setBounds(350, 65, 160, 25);
            principal_text.setText(Double.toString(principal));
            contentPanel.add(principal_text);


				//Mortgage Plan Label

				choose_label = new JLabel();
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            choose_label.setBounds(90, 125, 220, 25);
            choose_label.setText("Select Mortgage Plan : ");
            choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            choose_label.setForeground(Color.white);
            contentPanel.add(choose_label);

				//String for Mortgage Variation

            String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
				contentPanel.add(choose_combo);

				// Number of Years Label
			   years_label = new JLabel();
			   years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   years_label.setBounds(90, 200, 220, 25);
			   years_label.setText("Mortgage Term : ");
			   years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   years_label.setForeground(Color.white);
			   contentPanel.add(years_label);

			   // Number of Years Text Field
			   years_text = new JTextField();
			   years_text.setBounds(350, 205, 160, 25);
			   years_text.setText(Double.toString(number_years));
			   contentPanel.add(years_text);

			   // Annual Interest Rate Label
			   rate_label = new JLabel();
			   rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   rate_label.setBounds(90, 165, 220, 25);
			   rate_label.setText("Annunal Interest Rate : ");
			   rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   rate_label.setForeground(Color.white);
			   contentPanel.add(rate_label);

			   // Annual Interest Rate Text Field
			   rate_text = new JTextField();
			   rate_text.setBounds(350, 165, 160, 25);
			   rate_text.setText(Double.toString(interest_rate * 100) + "%");
			   contentPanel.add(rate_text);


            //Text Area for result

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


            // Button for reset button

            btnReset = new JButton ();
            btnReset.setBounds(355, 350, 110, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Button for calculation of the mortgage payments

            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 350,110, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


            // Action listener to the reset button

            btnReset.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                onButtonReset();
                 }
            });

     			//Button Press Calculate

            btnCalculate.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();

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

                          interest_rate = getDouble(rate_text.getText());
                       number_years =   Integer.parseInt(years_text.getText());
                     System.out.println(interest_rate);
						  //Calculates the number of months for mortgage so as to determine the number of payments to be made
                    number_of_months = number_years * 12;

                    //Calulates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Equation that calculates the monthly payment for 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



                    }


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


        }

        return contentPanel;
    }






    public double getDouble(String val) {
        double value = 00;
        try {
            // This tests to see if there is a dollar sign
            if (val.indexOf('$') > -1) {

                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {

				// Generates an error here

            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }


    public double getPercent(String val) {
        System.out.println(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(){
           principal_text.setText("");
           result.setText("");


    }


public static void main(String[] args) {

                SwingUtilities.invokeLater(new Runnable() {

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



   }

Open in new window

0
 
for_yanCommented:
This even gives reasonable numbers
but I didn't check logic - if you use both
droppwon and text - what happens?
anyway with "select morthage" in drpodown.
5.35% in the rate box and 10 in the term box
it returns:

Loan Amount = $100,000.00
Interest Rate = 5.35%
Length of Loan = 120 months
Monthly Payment = $1,077.85

Open in new window


/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4
Professor Matt Berg
May 2, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

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.JRadioButton;
import javax.swing.ButtonGroup;
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

public class GutierrezMortgageGui extends JFrame {

	static  String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
   static  String [] toReplace;
         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, scroll 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;
    		JRadioButton rbutton01 = null;
    		JRadioButton rbutton02 = null;
    		ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane

	 		JTextArea result = null;
    		JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane

    		JScrollPane scrolling_table = null;

    // Creates the button for calculation of the mortgage payments

    		JButton btnCalculate = null;

	 // Creates a button for reset button

			JButton btnReset = null;

	 //Variables

			int numberOfLinesGenerated=1;
        	int number_years; //Term of the mortgage
        	double principal; // Total amount borrowed
        	double interest_rate;  //  Interest rate for mortgage
        	double monthly_payment;  // Monthly payment amount for mortgage
        	double monthly_interest_rate ; // Monthly interest rate
        	int number_of_months; // 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 GutierrezMortgageGui() {
        	super();
        	initialize();
    }

	 //Window size, JPanel, setTitle

    	public void initialize() {
			this.setSize(700,500);
        	this.setContentPane(getJPanel());
        	this.setTitle("Gutierrez Mortgage GUI");
    }

    	public JPanel getJPanel() {
        	if (contentPanel == null) {
            contentPanel = new JPanel();
            contentPanel.setLayout(null);
            contentPanel.setBackground(Color.black);

            // GUI elements to display labels and fields for current information
				// to include Alignment, Boundary, Title, Font, Font Size, Color

            // Main Title of the Calculator
            main_title = new JLabel();
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            main_title.setBounds(130, 20, 400, 30);
            main_title.setText("My First GUI Loan Calculator");
            main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
            main_title.setForeground(Color.white);
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            principal_label.setBounds(90, 65, 220, 25);
            principal_label.setText("Mortgage Principle Amount : ");
            principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            principal_label.setForeground(Color.white);
            contentPanel.add(principal_label);

            //Principal Text Field Features

			   principal_text = new JTextField();
            principal_text.setBounds(350, 65, 160, 25);
            principal_text.setText(Double.toString(principal));
            contentPanel.add(principal_text);


				//Mortgage Plan Label

				choose_label = new JLabel();
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            choose_label.setBounds(90, 125, 220, 25);
            choose_label.setText("Select Mortgage Plan : ");
            choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
            choose_label.setForeground(Color.white);
            contentPanel.add(choose_label);

				//String for Mortgage Variation

            String mortgage[] = {"Select Mortgage","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
				contentPanel.add(choose_combo);

				// Number of Years Label
			   years_label = new JLabel();
			   years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   years_label.setBounds(90, 200, 220, 25);
			   years_label.setText("Mortgage Term : ");
			   years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   years_label.setForeground(Color.white);
			   contentPanel.add(years_label);

			   // Number of Years Text Field
			   years_text = new JTextField();
			   years_text.setBounds(350, 205, 160, 25);
			   years_text.setText(Double.toString(number_years));
			   contentPanel.add(years_text);

			   // Annual Interest Rate Label
			   rate_label = new JLabel();
			   rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			   rate_label.setBounds(90, 165, 220, 25);
			   rate_label.setText("Annunal Interest Rate : ");
			   rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			   rate_label.setForeground(Color.white);
			   contentPanel.add(rate_label);

			   // Annual Interest Rate Text Field
			   rate_text = new JTextField();
			   rate_text.setBounds(350, 165, 160, 25);
			   rate_text.setText(Double.toString(interest_rate * 100) + "%");
			   contentPanel.add(rate_text);


            //Text Area for result

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


            // Button for reset button

            btnReset = new JButton ();
            btnReset.setBounds(355, 350, 110, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // Button for calculation of the mortgage payments

            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 350,110, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


            // Action listener to the reset button

            btnReset.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                onButtonReset();
                 }
            });

     			//Button Press Calculate

            btnCalculate.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();

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

                          interest_rate = 0.01*getDouble(rate_text.getText());
                       number_years =   Integer.parseInt(years_text.getText());
                     System.out.println(interest_rate);
						  //Calculates the number of months for mortgage so as to determine the number of payments to be made
                    number_of_months = number_years * 12;

                    //Calulates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Equation that calculates the monthly payment for 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



                    }


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


        }

        return contentPanel;
    }






    public double getDouble(String val) {
        double value = 00;
        try {
            // This tests to see if there is a dollar sign
            if (val.indexOf('$') > -1) {

                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
                  System.out.println("v0:" + value);
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
                System.out.println("v1:" + value);
            }
        } catch (java.text.ParseException e) {

				// Generates an error here

            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }


    public double getPercent(String val) {
        System.out.println(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(){
           principal_text.setText("");
           result.setText("");


    }


public static void main(String[] args) {

                SwingUtilities.invokeLater(new Runnable() {

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



   }

Open in new window

0
 
objectsCommented:
> I understand, but I just can't get it to work. I need to override the combo like you said.

overriding the combo is messy (and then the combo stops working).
a better approach is to have the combo populate the text fileds (use a listener on the combo to do this)
0
 
objectsCommented:
Let me know if you need help implementing that, its not too hard
0
 
PapaDragonXAuthor Commented:
objects: i would not mind the help at all in implementing a combo populate, as you suggested.

for yan: thanks, it does work when i place the variables in the text box but would like to get the combo_box to work as well...i think objects is going to help me out unless you have an idea.

thanks guys...you are a big help to my scattered brain
0
 
objectsCommented:
The attached shows what I mean
the action listener on the combo populates the text fields
also moved some of your member vars into the calculate() method as they are only used there, keep things simpler
/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4
Professor Matt Berg
May 2, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class GutierrezMortgageGui extends JFrame {

	static String mortgage[] = { "Select Mortgage", "30 years at 5.75%" };
	static String[] toReplace;
	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, scroll 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;
	JRadioButton rbutton01 = null;
	JRadioButton rbutton02 = null;
	ButtonGroup buttongroup = null;

	// GUI text area for results with scroll pane

	JTextArea result = null;
	JScrollPane scrolling_result = null;

	// GUI for Table with scroll pane

	JScrollPane scrolling_table = null;

	// Creates the button for calculation of the mortgage payments

	JButton btnCalculate = null;

	// Creates a button for reset button

	JButton btnReset = null;

	// This is the class constructor - initialize the components

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

	// Window size, JPanel, setTitle

	public void initialize() {
		this.setSize(700, 500);
		this.setContentPane(getJPanel());
		this.setTitle("Gutierrez Mortgage GUI");
	}

	public JPanel getJPanel() {
		if (contentPanel == null) {
			contentPanel = new JPanel();
			contentPanel.setLayout(null);
			contentPanel.setBackground(Color.black);

			// GUI elements to display labels and fields for current information
			// to include Alignment, Boundary, Title, Font, Font Size, Color

			// Main Title of the Calculator
			main_title = new JLabel();
			main_title.setHorizontalAlignment(SwingConstants.CENTER);
			main_title.setBounds(130, 20, 400, 30);
			main_title.setText("My First GUI Loan Calculator");
			main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
			main_title.setForeground(Color.white);
			contentPanel.add(main_title);

			// Principal Label
			principal_label = new JLabel();
			principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
			principal_label.setBounds(90, 65, 220, 25);
			principal_label.setText("Mortgage Principle Amount : ");
			principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principal_label.setForeground(Color.white);
			contentPanel.add(principal_label);

			// Principal Text Field Features

			principal_text = new JTextField();
			principal_text.setBounds(350, 65, 160, 25);
			// principal_text.setText(Double.toString(principal));
			contentPanel.add(principal_text);

			// Mortgage Plan Label

			choose_label = new JLabel();
			choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
			choose_label.setBounds(90, 125, 220, 25);
			choose_label.setText("Select Mortgage Plan : ");
			choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			choose_label.setForeground(Color.white);
			contentPanel.add(choose_label);

			// String for Mortgage Variation

			String mortgage[] = { "Select Mortgage", "30 years at 5.75%" };
			choose_combo = new JComboBox(mortgage);
			choose_combo.setBounds(350, 125, 180, 30);
			choose_combo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			contentPanel.add(choose_combo);

			// Number of Years Label
			years_label = new JLabel();
			years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			years_label.setBounds(90, 200, 220, 25);
			years_label.setText("Mortgage Term : ");
			years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			years_label.setForeground(Color.white);
			contentPanel.add(years_label);

			// Number of Years Text Field
			years_text = new JTextField();
			years_text.setBounds(350, 205, 160, 25);
			contentPanel.add(years_text);

			// Annual Interest Rate Label
			rate_label = new JLabel();
			rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			rate_label.setBounds(90, 165, 220, 25);
			rate_label.setText("Annunal Interest Rate : ");
			rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			rate_label.setForeground(Color.white);
			contentPanel.add(rate_label);

			// Annual Interest Rate Text Field
			rate_text = new JTextField();
			rate_text.setBounds(350, 165, 160, 25);
			contentPanel.add(rate_text);

			// Text Area for result

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

			// Button for reset button

			btnReset = new JButton();
			btnReset.setBounds(355, 350, 110, 30);
			btnReset.setText("Reset");
			contentPanel.add(btnReset);

			// Button for calculation of the mortgage payments

			btnCalculate = new JButton();
			btnCalculate.setBounds(245, 350, 110, 30);
			btnCalculate.setText("Calculate");
			contentPanel.add(btnCalculate);

			// Action listener to the reset button

			btnReset.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonReset();
				}
			});

			// Button Press Calculate

			btnCalculate.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					calculate();
				}

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

		}

		return contentPanel;
	}

	private void setMortgage() {
		String str = (String) choose_combo.getSelectedItem();

		if (str.equals("30 years at 5.75%")) {
			rate_text.setText("0.0575");
			years_text.setText("30");
		}

	}

	public double getDouble(String val) {
		double value = 00;
		try {
			// This tests to see if there is a dollar sign
			if (val.indexOf('$') > -1) {

				value = NumberFormat.getCurrencyInstance().parse(val)
						.doubleValue();
			} else {
				value = NumberFormat.getNumberInstance().parse(val)
						.doubleValue();
			}
		} catch (java.text.ParseException e) {

			// Generates an error here

			JOptionPane.showMessageDialog(this, "There is an error " + val
					+ ". Please check your entry", "Data Entry Error",
					JOptionPane.ERROR_MESSAGE);
		}
		return value;
	}

	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() {
		principal_text.setText("");
		result.setText("");

	}

	private void calculate() {
		double principal = getDouble(principal_text.getText());
		int number_of_years = Integer.parseInt(years_text.getText());
		double interest_rate = getDouble(rate_text.getText());

		// Calculates the number of months for mortgage so as to
		// determine the number of payments to be made
		int number_of_months = number_of_years * 12;

		// Calulates the monthly interest rate
		double monthly_interest_rate = interest_rate / 12.0;

		// Equation that calculates the monthly payment for mortgage
		double 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_of_years * 12.0)
				+ " months" + "\nMonthly Payment = "
				+ money.format(monthly_payment)); // calling the
													// monthly_payment
	}

	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {

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

}

Open in new window

0
 
PapaDragonXAuthor Commented:
Thank you both for your help!  I noticed where the action listener was implemented and how useful this is.  I will adjust the button that resets the fields so it will reset all fields.  Thanks again!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 5
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now