Advertisement
Guest User

Untitled

a guest
May 7th, 2010
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.41 KB | None | 0 0
  1. /*  
  2.     File: MortgageCalculator2.java
  3.     This file calculates the monthly payments of a user inputs for a mortgage.
  4. */
  5.  
  6. import javax.swing.*;
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import java.text.DecimalFormat;
  10.  
  11. /* import java package: classes to handle I/O methods,
  12. including FileReader, InputStreamReader, and BufferedReader.
  13. */                                                 
  14.  
  15. @SuppressWarnings("serial")
  16. public class MortgageCalculator3 extends JFrame implements ActionListener
  17. {
  18.     int financeYears;
  19.     double interestRate;
  20.     int salary;
  21.     double loan;
  22.     double rate;
  23.     double yearlyPmt;
  24.     double[] monthlyPmt, principal, loanPmt, ratePmt, newPrincipal;
  25.     double endPrincipal;
  26.     boolean calculate = false;
  27.     boolean next = false;
  28.     boolean previous = false;
  29.     //variables
  30.     int yearNumber = 1;
  31.     int periodNumber = 1;
  32.     int month = 0;
  33.     int currMonth = 0;
  34.     double interestPerYear = 0;
  35.     DecimalFormat df = new DecimalFormat("###,###.00");
  36.    
  37.    
  38.    
  39.     //layout preparation
  40.     LoanLayout customLayout = new LoanLayout();
  41.            
  42.         JLabel loanLabel = new JLabel("Loan Amount");
  43.        
  44.             JTextField loanText = new JTextField();
  45.        
  46.         JLabel termLabel = new JLabel("Years Financed");
  47.        
  48.             JTextField termText = new JTextField();
  49.        
  50.         JLabel rateLabel = new JLabel("Interest Rate (x.xx)");
  51.        
  52.             JTextField rateText = new JTextField();
  53.            
  54.         JLabel salaryLabel = new JLabel("Annual Salary");
  55.        
  56.             JTextField salaryText = new JTextField();
  57.        
  58.         JLabel monthlyLabel = new JLabel("Monthly Payment");
  59.        
  60.             JTextField monthlyText = new JTextField();
  61.            
  62.         JLabel yearTotalLabel = new JLabel("Year Total");
  63.        
  64.             JTextField yearTotalText = new JTextField();
  65.            
  66.         JLabel salaryTaxLabel = new JLabel("Salary After Taxes");
  67.        
  68.             JTextField salaryTaxText = new JTextField();
  69.            
  70.         JLabel salPercentLabel = new JLabel("Salary Percent of Yearly Mortgage");
  71.        
  72.             JTextField salPercentText = new JTextField();
  73.        
  74.         JLabel scheduleLabel = new JLabel("Schedule");
  75.        
  76.             JTextArea scheduleText = new JTextArea();
  77.            
  78.             JScrollPane scroller = new JScrollPane(scheduleText);
  79.            
  80.     public MortgageCalculator3()
  81.     {
  82.         JButton calcButton = new JButton("Calculate");
  83.        
  84.         JButton resetButton = new JButton("Reset");
  85.        
  86.         JButton scheduleButton = new JButton("Show Schedule");
  87.        
  88.         JButton previousButton = new JButton("<< Previous Year");
  89.        
  90.         JButton nextButton = new JButton("Next Year >>");
  91.        
  92.         JButton exitButton = new JButton("Exit");
  93.        
  94.         //add ActionListener to buttons
  95.         calcButton.addActionListener(this);
  96.         resetButton.addActionListener(this);
  97.         scheduleButton.addActionListener(this);
  98.         previousButton.addActionListener(this);
  99.         nextButton.addActionListener(this);
  100.         exitButton.addActionListener(this);
  101.        
  102.         //add ActionCommand to buttons
  103.         calcButton.setActionCommand("calculate");
  104.         resetButton.setActionCommand("reset");
  105.         scheduleButton.setActionCommand("show");
  106.         previousButton.setActionCommand("previous");
  107.         nextButton.setActionCommand("next");
  108.         exitButton.setActionCommand("exit");
  109.        
  110.         //getContentPane, set editable & setText for all labels, fields, and buttons
  111.         getContentPane().setLayout(customLayout);
  112.         getContentPane().add(loanLabel);
  113.         getContentPane().add(loanText);
  114.         getContentPane().add(termLabel);
  115.         getContentPane().add(termText);
  116.         getContentPane().add(rateLabel);
  117.         getContentPane().add(rateText);
  118.         getContentPane().add(salaryLabel);
  119.         getContentPane().add(salaryText);
  120.         getContentPane().add(calcButton);
  121.         getContentPane().add(resetButton);
  122.         getContentPane().add(monthlyLabel);
  123.         getContentPane().add(monthlyText);
  124.         monthlyText.setEditable(false);
  125.         getContentPane().add(yearTotalLabel);
  126.         getContentPane().add(yearTotalText);
  127.         yearTotalText.setEditable(false);
  128.         getContentPane().add(salaryTaxLabel);
  129.         getContentPane().add(salaryTaxText);
  130.         salaryTaxText.setEditable(false);
  131.         getContentPane().add(salPercentLabel);
  132.         getContentPane().add(salPercentText);
  133.         getContentPane().add(scheduleButton);
  134.         salPercentText.setEditable(false);
  135.         getContentPane().add(scheduleLabel);
  136.         getContentPane().add(scroller);
  137.         scheduleText.setEditable(false);
  138.         getContentPane().add(previousButton);
  139.         getContentPane().add(nextButton);
  140.         getContentPane().add(exitButton);
  141.        
  142.         //added this to ensure that the Frame closes properly  
  143.         addWindowListener(new WindowAdapter()
  144.             {
  145.                 public void windowClosing(WindowEvent e)
  146.                 {  
  147.                     System.exit(0);
  148.                 }
  149.             }
  150.             );
  151.     }
  152.    
  153.     //actionPerformed          
  154.     public void actionPerformed(ActionEvent e)
  155.     {
  156.         String arg = e.getActionCommand();
  157.         if (arg == "calculate" )
  158.         {
  159.             scheduleText.setText("");
  160.            
  161.             try
  162.             {
  163.                 loan = Double.parseDouble(loanText.getText());
  164.                 financeYears = Integer.parseInt(termText.getText());
  165.                 rate = Double.parseDouble(rateText.getText());
  166.                 salary = Integer.parseInt(salaryText.getText());
  167.             }
  168.             catch (Exception ex)
  169.             {
  170.                 JOptionPane.showMessageDialog(null, "Invalid mortgage, term, rate, or salary amount\nFill out all above fields","Error", JOptionPane.ERROR_MESSAGE);
  171.                 return;
  172.             }
  173.            
  174.             calculate = true;
  175.             rate = rate / 100;
  176.             endPrincipal = loan;
  177.             DecimalFormat df1 = new DecimalFormat("###,###.000");
  178.            
  179.             monthlyPmt = new double[(int) (12 * financeYears + 1)];
  180.             principal = new double[(int) (12 * financeYears + 1)];
  181.            
  182.             for (int i = 0; i < monthlyPmt.length; i++)
  183.             {
  184.                 principal[i] = loan;
  185.                 monthlyPmt[i] = (double) Math.round((rate / 12 * principal[i] * (Math.pow(1 + rate / 12,financeYears * 12)))/(Math.pow((1 + rate / 12),financeYears * 12) -1) * 100) / 100;
  186.                 yearlyPmt = (monthlyPmt[i] * 12);
  187.             }
  188.             int[] bracketRange = {0, 8375, 34000, 82400, 171850, 373650};
  189.             double[] taxBracket = {0.90, 0.85, 0.75, 0.72, 0.67, 0.65};
  190.             double afterTaxes = 0;
  191.             double salaryPercent = 0;
  192.             if (salary >= bracketRange[5])
  193.             {
  194.                 salaryPercent = (yearlyPmt / (salary * taxBracket[5] / 100));
  195.                 afterTaxes = salary * taxBracket[5];
  196.             }
  197.             if (salary >= bracketRange[4] && salary < bracketRange[5])
  198.             {
  199.                 salaryPercent = (yearlyPmt / (salary * taxBracket[4] / 100));
  200.                 afterTaxes = salary * taxBracket[4];
  201.             }
  202.             if (salary >= bracketRange[3] && salary < bracketRange[4])
  203.             {
  204.                 salaryPercent = (yearlyPmt / (salary * taxBracket[3] / 100));
  205.                 afterTaxes = salary * taxBracket[3];
  206.             }
  207.             if (salary >= bracketRange[2] && salary < bracketRange[3])
  208.             {
  209.                 salaryPercent = (yearlyPmt / (salary * taxBracket[2] / 100));
  210.                 afterTaxes = salary * taxBracket[2];
  211.             }
  212.             if (salary >= bracketRange[1] && salary < bracketRange[2])
  213.             {
  214.                 salaryPercent = (yearlyPmt / (salary * taxBracket[1] / 100));
  215.                 afterTaxes = salary * taxBracket[1];
  216.             }
  217.             if (salary >= bracketRange[0] && salary < bracketRange[1])
  218.             {
  219.                 salaryPercent = (yearlyPmt / (salary * taxBracket[0] / 100));
  220.                 afterTaxes = salary * taxBracket[0];
  221.             }
  222.            
  223.             monthlyText.setText("$" + df.format(monthlyPmt[0]));
  224.             yearTotalText.setText("$" + df.format(yearlyPmt));
  225.             salaryTaxText.setText("$" + df.format(afterTaxes));
  226.             salPercentText.setText(df1.format(salaryPercent) + "%");
  227.         }
  228.         //if reset button is picked, fields are cleared.
  229.         if (arg == "reset")
  230.         {
  231.             calculate = false;
  232.             loanText.setText("");
  233.             termText.setText("");
  234.             rateText.setText("");
  235.             salaryText.setText("");
  236.             monthlyText.setText("");
  237.             yearTotalText.setText("");
  238.             salaryTaxText.setText("");
  239.             salPercentText.setText("");
  240.             scheduleText.setText("");
  241.             yearNumber = 1;
  242.         }
  243.         //if show button is picked, year 1 is shown in the schedule area
  244.         if (arg == "show")
  245.         {
  246.             if (calculate)
  247.             {
  248.                 createSchedule(monthlyPmt, principal, financeYears, rate);
  249.                 interestPerYear = 0;
  250.                 yearNumber = 1;
  251.                 populateSchedule(yearNumber);
  252.             }
  253.         }
  254.         //if previous button is picked, schedule goes back 1 year
  255.         if (arg == "previous")
  256.         {
  257.             previous = true;
  258.             if (yearNumber > 1)
  259.             {
  260.                 yearNumber = yearNumber - 1;
  261.                 populateSchedule(yearNumber);
  262.             }
  263.             else
  264.                 JOptionPane.showMessageDialog(null, "Cannot go back, already on Year 1","Error", JOptionPane.ERROR_MESSAGE);
  265.         }
  266.         //if next button is picked, schedule goes forward 1 year
  267.         if (arg == "next")
  268.         {
  269.             next = true;
  270.             if (yearNumber < financeYears)
  271.             {
  272.                 yearNumber = yearNumber + 1;
  273.                 populateSchedule(yearNumber);
  274.                
  275.             }
  276.             else
  277.                 JOptionPane.showMessageDialog(null, "Cannot continue forward, reached maximum year","Error", JOptionPane.ERROR_MESSAGE);
  278.         }
  279.         //if exit button is picked, program closes
  280.         if (arg == "exit")
  281.         {
  282.             System.exit(0);
  283.         }
  284.        
  285.     }
  286.     public static void main(String[] args)                     
  287.     {                                                                                  
  288.         //creating the JFrame window
  289.         {
  290.             new MortgageCalculator3();
  291.             JFrame nFrame = new MortgageCalculator3();
  292.             nFrame.setVisible(true);
  293.             nFrame.setTitle("Mortgage Calculator");
  294.             nFrame.setSize(650,770);
  295.             nFrame.setLocation(600,200);
  296.         }
  297.     }
  298.     public void createSchedule(double monthlyPmt[], double principal[], double financeYears, double rate)
  299.     {  
  300.         loanPmt = new double[(int) (12 * financeYears + 1)];
  301.         ratePmt = new double[(int) (12 * financeYears + 1)];
  302.         newPrincipal = new double[(int) (12 * financeYears + 1)];
  303.         for (yearNumber = 1; yearNumber <= financeYears; yearNumber++)
  304.         {
  305.             for (int periodNumber = 1; periodNumber <= 12; periodNumber++)
  306.             {
  307.                 month = (12 * (yearNumber - 1)) + periodNumber - 1;
  308.                 double d = (double) Math.round((principal[month] * rate / 12) * 100) / 100;
  309.                 ratePmt[month] = d;
  310.                 System.out.println(ratePmt[month]);
  311.                 loanPmt[month] = (double) Math.round((monthlyPmt[month] - ratePmt[month]) * 100) / 100;
  312.                 newPrincipal[month] = (double) Math.round((principal[month] - loanPmt[month]) * 100) / 100;
  313.                 principal[month + 1] = newPrincipal[month];
  314.             }
  315.             principal[month + 1] = newPrincipal[month];
  316.         }
  317.     }
  318.     public void populateSchedule(int yearNumber)  // Places the values for a given year of the loan into the schedule
  319.     {
  320.             if (yearNumber >= 10)
  321.                 scheduleText.append("\t\t                   Year " + yearNumber + "\n\t\t                   ********");
  322.             else
  323.                 scheduleText.append("\t\t                    Year " + yearNumber + "\n\t\t                    *******");
  324.             scheduleText.append("\nMONTH\tBEG BALANCE\tLOAN\tRATE\tTOTAL\tEND BALANCE");
  325.             for (int periodNumber = 1; periodNumber <= 12; periodNumber++)
  326.             {
  327.                 currMonth = 12 * (yearNumber - 1) + periodNumber - 1;
  328.                 //for last few payments, so the balance doesn't go in the negative
  329.                 if (newPrincipal[currMonth] < 0)
  330.                 {
  331.                     newPrincipal[currMonth] = 0;
  332.                     loanPmt[currMonth] = principal[currMonth] - ratePmt[currMonth];
  333.                     monthlyPmt[currMonth] = loanPmt[currMonth] + ratePmt[currMonth];
  334.                 }
  335.                 scheduleText.append("\n" + (currMonth + 1) + "\t$" + (df.format(principal[currMonth])) + " \t$" + (df.format(loanPmt[currMonth])) + "\t$" + (df.format(ratePmt[currMonth])) + "\t$" + (df.format(monthlyPmt[currMonth])) + "\t$" + (df.format(newPrincipal[currMonth])));
  336.                 principal[currMonth + 1] = newPrincipal[currMonth];
  337.            
  338.                 if (yearNumber <= financeYears)
  339.                     interestPerYear += ratePmt[currMonth];
  340.             }
  341.             if (yearNumber < financeYears)
  342.                 scheduleText.append("\n\nTotal interest paid so far is: $" + df.format(interestPerYear));
  343.             else
  344.             {
  345.                 scheduleText.append("\n\nTotal interest paid: $" + df.format(interestPerYear));
  346.                 scheduleText.append("\nTotal cost of home: $" + df.format(endPrincipal + interestPerYear) + " after " + (yearNumber) + " years");
  347.             }
  348.             scheduleText.append("\n\n");
  349.     }
  350.    
  351.     //Layout manager
  352.     class LoanLayout implements LayoutManager
  353.     {
  354.         public LoanLayout()
  355.         {
  356.         }
  357.         public void addLayoutComponent(String name, Component comp)
  358.         {
  359.         }
  360.         public void removeLayoutComponent(Component comp)
  361.         {
  362.         }
  363.        
  364.         // layout dimensions
  365.         public Dimension preferredLayoutSize(Container parent)
  366.         {
  367.             Dimension dim = new Dimension(0, 0);
  368.                 Insets insets = parent.getInsets();
  369.                  dim.height = 770 + insets.top + insets.bottom;    //height of window
  370.                  dim.width = 650 + insets.left + insets.right;     // width of window
  371.             return dim;
  372.         }
  373.        
  374.         public Dimension minimumLayoutSize(Container parent)
  375.         {
  376.             Dimension dim = new Dimension(0, 0);
  377.             return dim;
  378.         }
  379.        
  380.         // arrangement of all components (JButton, JTextField, and JLabel) in window as listed above
  381.         public void layoutContainer(Container parent)
  382.         {
  383.             Insets insets = parent.getInsets();
  384.            
  385.             Component w;  // array for components (JButton, JTextField, and JLabel)
  386.             w = parent.getComponent(0);
  387.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+20,130,20);} //loan label
  388.             w = parent.getComponent(1);
  389.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+20,100,20);} // loan field
  390.             w = parent.getComponent(2);
  391.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+50,130,20);} // term label
  392.             w = parent.getComponent(3);
  393.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+50,100,20);} // term field
  394.             w = parent.getComponent(4);
  395.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+80,130,20);} // rate label
  396.             w = parent.getComponent(5);
  397.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+80,100,20);}  // rate field
  398.             w = parent.getComponent(6);
  399.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+110,160,20);} // salary label
  400.             w = parent.getComponent(7);
  401.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+110,100,20);}  // salary field
  402.             w = parent.getComponent(8);
  403.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+150,120,30);}  // calculate button
  404.             w = parent.getComponent(9);
  405.             if (w.isVisible()) {w.setBounds(insets.left+150,insets.top+150,100,30);}  // reset button
  406.             w = parent.getComponent(10);
  407.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+200,140,20);}  // payment label
  408.             w = parent.getComponent(11);
  409.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+200,100,20);}  // payment field
  410.             w = parent.getComponent(12);
  411.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+230,140,20);}  // yearTotal label
  412.             w = parent.getComponent(13);
  413.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+230,100,20);}  // yearTotal field
  414.             w = parent.getComponent(14);
  415.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+260,140,20);}  // salaryTax label
  416.             w = parent.getComponent(15);
  417.             if (w.isVisible()) {w.setBounds(insets.left+170,insets.top+260,100,20);}  // salaryTax field
  418.             w = parent.getComponent(16);
  419.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+290,210,20);}  // salPercent label
  420.             w = parent.getComponent(17);
  421.             if (w.isVisible()) {w.setBounds(insets.left+240,insets.top+290,80,20);}  // salPercent field
  422.             w = parent.getComponent(18);
  423.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+320,200,30);}  // show button
  424.             w = parent.getComponent(19);
  425.             if (w.isVisible()) {w.setBounds(insets.left+285,insets.top+340,80,20);}  // schedule label
  426.             w = parent.getComponent(20);
  427.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+370,610,300);}  // schedule field
  428.             w = parent.getComponent(21);
  429.             if (w.isVisible()) {w.setBounds(insets.left+20,insets.top+680,150,30);}  // previous button
  430.             w = parent.getComponent(22);
  431.             if (w.isVisible()) {w.setBounds(insets.left+480,insets.top+680,150,30);}  // next button
  432.             w = parent.getComponent(23);
  433.             if (w.isVisible()) {w.setBounds(insets.left+285,insets.top+690,80,50);}  // exit button
  434.         }
  435.     }
  436. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement