package mortgagecalc;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Canvas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.border.LineBorder;
public class MortgageCalc extends JFrame {
String mortgage[] = { "Select Mortgage" };
//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 mainTitle = null;
JLabel principalLabel = null;
JTextField principalText = null;
JLabel yearsLabel = null;
JTextField yearsText = null;
JLabel rateLabel = null;
JTextField rateText = null;
JLabel chooseLabel = null;
JComboBox chooseCombo = null;
JRadioButton selectionOne = null;
JRadioButton selectionTwo = null;
ButtonGroup buttongroup = null;
// GUI text area for results with scroll pane
JTextArea result = null;
JTextArea GraphArea = new JTextArea(19,50);
JScrollPane scrollingResults = null;
// GUI for Table with scroll pane
MyJTable totalAmounts = null;
JScrollPane scrollingTable = null;
MyDTableModel model;
// Creates button for graphing
JButton graphButton = null;
// Creates the button for calculation of the mortgage payments
JButton calculateButton = null;
// Creates a button for reset button
JButton resetButton = null;
// Declaration of variables
int numberOfLinesGenerated=1;
double numberYears; //term mortgage
double principal; // amount borrowed
double rate; // interest for mortgage
double monthlyPayment; // monthly payment for mortgage
double monthlyRate ; // monthly interest
double totalMonths; // number of months for mortgage payments
double interestPaid; //interest amount added for each month
double principalPaid;
// This is the class constructor - initialize the components
public MortgageCalc() {
super();
initialize();
}
// Window size, JPanel, setTitle
public void initialize() {
this.setSize(720, 670);
this.setContentPane(getJPanel());
this.setTitle("Mortgage Calculator by Luther Mann");
}
public JPanel getJPanel() {
if (contentPanel == null) {
readFile();
contentPanel = new JPanel();
contentPanel.setLayout(null);
contentPanel.setBackground(Color.LIGHT_GRAY);
// GUI elements to display labels and fields for current information
// to include Alignment, Boundary, Title, Font, Font Size, Color
// Main Title of the Calculator
mainTitle = new JLabel();
mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
mainTitle.setBounds(130, 20, 400, 30);
mainTitle.setText("Luther's Loan Calculator");
mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
mainTitle.setForeground(Color.blue);
contentPanel.add(mainTitle);
//Selection button 1
selectionOne = new JRadioButton();
selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
selectionOne.setBounds(125, 65, 160, 15);
selectionOne.setText("Preset Loan Terms");
selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
selectionOne.setForeground(Color.black);
selectionOne.setSelected(true);
contentPanel.add(selectionOne);
//Selection Button 2
selectionTwo = new JRadioButton();
selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
selectionTwo.setBounds(350, 65, 180, 15);
selectionTwo.setText("Enter Your Loan Terms");
selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
selectionTwo.setForeground(Color.black);
contentPanel.add(selectionTwo);
// Principal Label
principalLabel = new JLabel();
principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
principalLabel.setBounds(120, 65, 200, 75);
principalLabel.setText("Mortgage Principle Amount : ");
principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
principalLabel.setForeground(Color.blue);
contentPanel.add(principalLabel);
// Principal Text Field Features
principalText = new JTextField();
principalText.setBounds(350, 90, 160, 25);
contentPanel.add(principalText);
// Mortgage Plan Label
chooseLabel = new JLabel();
chooseLabel.setHorizontalAlignment(SwingConstants.RIGHT);
chooseLabel.setBounds(90, 125, 220, 25);
chooseLabel.setText("Select Mortgage Plan : ");
chooseLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
chooseLabel.setForeground(Color.blue);
contentPanel.add(chooseLabel);
// String for Mortgage Variation
Mortgage[] mortgage = new mortgage(0);
mortgage(0) = {"Select Mortgage"};
for (int i = 0; i less than terms.length; i++)
{
Mortgage[i] = years[i] + “years…” + terms[i] + “%”;
}
chooseCombo = new JComboBox(mortgage);
chooseCombo.setBounds(350, 125, 180, 30);
chooseCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setMortgage();
}
});
contentPanel.add(chooseCombo);
// Text Area for result
result = new JTextArea(5, 20);
result.setEditable(false);
result.setBounds(170, 250, 350, 75);
scrollingResults = new JScrollPane(result);
contentPanel.add(result);
//Table for amortization calculations
totalAmounts = new MyJTable();
scrollingTable = new JScrollPane (totalAmounts);
scrollingTable.setBounds(25, 425, 600, 175);
contentPanel.add(scrollingTable);
// Number of Years Label
yearsLabel = new JLabel();
yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
yearsLabel.setBounds(90, 200, 220, 25);
yearsLabel.setText("Mortgage Term : ");
yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
yearsLabel.setForeground(Color.blue);
yearsLabel.setVisible(false);
contentPanel.add(yearsLabel);
// Number of Years Text Field
yearsText = new JTextField();
yearsText.setBounds(350, 205, 160, 25);
yearsText.setVisible(false);
yearsText.setEditable(false);
contentPanel.add(yearsText);
// Annual Interest Rate Label
rateLabel = new JLabel();
rateLabel.setHorizontalAlignment(SwingConstants.RIGHT);
rateLabel.setBounds(90, 165, 220, 25);
rateLabel.setText("Annual Interest Rate(Decimal) : ");
rateLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
rateLabel.setForeground(Color.blue);
rateLabel.setVisible(false);
contentPanel.add(rateLabel);
// Annual Interest Rate Text Field
rateText = new JTextField();
rateText.setBounds(350, 165, 160, 25);
rateText.setEditable(false);
rateText.setVisible(false);
contentPanel.add(rateText);
// Button for Graphing
graphButton = new JButton();
graphButton.setBounds(395, 350, 110, 30);
graphButton.setText("Graph");
contentPanel.add(graphButton);
// Button for reset button
resetButton = new JButton();
resetButton.setBounds(285, 350, 110, 30);
resetButton.setText("Reset");
contentPanel.add(resetButton);
// Button for calculation of the mortgage payments
calculateButton = new JButton();
calculateButton.setBounds(175, 350, 110, 30);
calculateButton.setText("Calculate");
contentPanel.add(calculateButton);
// ---- Radio Button Listeners
selectionOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
hideSelectionTwo();
}
});
selectionTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// ---- display results
displaySelectionTwo();
}
});
// Action listener to the reset button
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onButtonreset();
}
});
graphButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawGraph();
}
});
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
principal=getDouble(principalText.getText());
calculate();
{
//Gets the values from the combo box or text box
if (selectionOne.isSelected()){
String str = (String)chooseCombo.getSelectedItem();
if (str.equals("30 years at 5.75%")) {
rate = 0.0575;
numberYears = 30;
}
else
if(str.equals("20 years at 5.65%")) {
rate = 0.0565;
numberYears = 20;
}
else
if(str.equals("10 years at 5%")) {
rate = 0.055;
numberYears = 10;
}
else
if(str.equals("7 years at 5.35%")) {
rate = 0.0535;
numberYears = 7;
}
}
else {
rate = Double.parseDouble(rateText.getText());
numberYears = Double.parseDouble(yearsText.getText());
rate = rate/100;
}
}
//Calculates the number of months for mortgage
totalMonths = numberYears * 12;
//Caluclates the monthly interest rate
monthlyRate = rate/12.0;
//Calculates the monthly payment for mortgage
monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));
// Sets the result text
result.setText("Loan Amount = " + money.format(principal)
+"\nInterest Rate = " + (rate * 100) +"%"+"\nLength of Loan = "
+ Math.round(numberYears * 12.0) + " months"+"\nMonthly Payment = "
+ money.format(monthlyPayment)); //calling the monthlyPayment
// Have the necessary information for the model lets recalculate it.
if(totalAmounts != null){
totalAmounts.setModel(getModel());
}
}
});
//Adds the calculate button
contentPanel.add(calculateButton);
//Adds the scroll pane
contentPanel.add(getScrollPane());
}
return contentPanel;
}
public void readFile()
{
String dataFileName = "/loandata.txt";
//create arrays to hold values in file
final ArrayList<Double> rateList = new ArrayList<Double>();
final ArrayList<Integer> yearList = new ArrayList<Integer>();
//open and read text file
try
{
BufferedReader br = new BufferedReader(new FileReader(dataFileName));
String line;
while ((line = br.readLine()) != null)
{
String values[] = line.split(","); //splits each word after comma and stores values in array "values"
int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line
yearList.add(value1); //adds all value1 integers to arraylist
rateList.add(value2); //adds all value2 doubles to arraylist
}
br.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//setMortgage Calculation//
public void setMortgage() {
String str = (String) chooseCombo.getSelectedItem();
if (str.equals("30 years at 5.75%")) {
rateText.setText("0.0575");
yearsText.setText("30");
}
else
if(str.equals("20 years at 5.65%")) {
rateText.setText("0.0565");
yearsText.setText("20");
}
else
if(str.equals("10 years at 5%")) {
rateText.setText("0.05");
yearsText.setText("10");
}
else
if(str.equals("7 years at 5.35%")) {
rateText.setText("0.0535");
yearsText.setText("7");
}
}
// Information for Reset Button//
public void onButtonreset() {
principalText.setText("");
rateText.setText("");
yearsText.setText("");
result.setText("");
model.setRowCount(0);
}
// Calculate() call//
public void calculate() {
double principal = getDouble(principalText.getText());
int number_of_years = Integer.parseInt(yearsText.getText());
double interest_rate = getDouble(rateText.getText());
if(interest_rate > 1.0)interest_rate = interest_rate/100.0;
// 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));
GraphArea.append("" + principalPaid);
// monthlyPayment
}
// This the Scroll pane for the table - sets the boundaries//
public JScrollPane getScrollPane() {
if (scrollingTable == null) {
scrollingTable = new JScrollPane();
scrollingTable.setBounds(65, 225, 425, 120);
scrollingTable.setViewportView(getTable());
}
return scrollingTable;
}
public JTable getTable() {
if (totalAmounts == null) {
totalAmounts = new MyJTable(getModel());
}
return totalAmounts;
}
//This will calculate the model for the table//
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 && rate != 0 && numberYears != 0) {
double new_principal = principal;
NumberFormat nf = NumberFormat.getCurrencyInstance();
for (int i = 0; i < totalMonths; i++) {
Object data[] = new Object[6];
data[0] = Integer.toString(i + 1);
data[1] = nf.format(new_principal);
data[2] = nf.format(monthlyPayment);
data[3] = nf.format(interestPaid = principal * monthlyRate);
data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
data[5] = nf.format(principal = principal - principalPaid);
new_principal = principal;
model.addRow(data);
}
}
return model;
}
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;
}
//main() method//
public static void main(String[] args) {
// Using Nimbus "Look and Feel" to make the layout more appealing.
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() {
MortgageCalc thisClass = new MortgageCalc();
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);
}
}
//used to hide and show the correct components
public void displaySelectionTwo() {
chooseCombo.setVisible(false);
selectionTwo.setSelected(true);
selectionOne.setSelected(false);
yearsLabel.setVisible(true);
yearsLabel.setText("Loan Term Years: ");
yearsText.setVisible(true);
yearsText.setEditable(true);
rateText.setVisible(true);
rateText.setEditable(true);
rateLabel.setVisible(true);
chooseLabel.setVisible(false);
rateLabel.setText("Interest Rate :");
}
public void hideSelectionTwo() {
chooseCombo.setVisible(true);
selectionTwo.setSelected(false);
selectionOne.setSelected(true);
principalLabel.setText("Please Select Loan: ");
rateLabel.setVisible(false);
yearsLabel.setText("Years: ");
yearsLabel.setVisible(false);
yearsText.setVisible(false);
yearsText.setColumns(10);
rateLabel.setText("Interest Rate: ");
rateLabel.setVisible(false);
rateText.setVisible(false);
yearsText.setColumns(10);
chooseLabel.setVisible(true);
}
public void drawGraph() // this will draw the graph "somehow"
{
}
public class GraphProgram extends JPanel
{
GraphProgram.GraphCanvas graph = new GraphProgram.GraphCanvas();
public GraphProgram()
{
setLayout(new BorderLayout());
setSize(300, 300);
add(graph, BorderLayout.CENTER);
}
public void setValues(double[] values) {
graph.setValues(values);
}
public class CoordCanvas extends Canvas
{
protected float viewLeft;
protected float viewRight;
protected float viewTop;
protected float viewBottom;
public void setXRange(float left, float right)
{
viewLeft = left;
viewRight = right;
}
public void setYRange(float top, float bottom)
{
viewTop = top;
viewBottom = bottom;
}
public float toX(float x)
{
return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
}
public float toY(float y)
{
return (y - viewTop) * getSize().height / (viewBottom - viewTop);
}
public float toWidth(float w)
{
return w * getSize().width / Math.abs(viewRight - viewLeft);
}
public float toHeight(float h)
{
return h * getSize().height / Math.abs(viewBottom - viewTop);
}
}
// subclass to draw a bar graph
class GraphCanvas extends GraphProgram.CoordCanvas
{
private double[] vals = null;
public void setValues(double[] vals)
{
this.vals = vals;
repaint();
}
public void paint(Graphics comp)
{
if (vals == null || vals.length < 1)
return;
// find maximum value
double max = vals[0];
for (int i = 0; i < vals.length; i++)
if (vals[i] > max)
max = vals[i];
// set coordinate ranges
this.setXRange(0F, (float)vals.length);
this.setYRange((float)max, 0F);
// draw the graph
Graphics2D comp2D = (Graphics2D)comp;
for (int i = 0; i < vals.length; i++)
{
Rectangle2D.Float principal = new Rectangle2D.Float(toX((float)i),
toY((float)vals[i]), toWidth(1F), toHeight((float)vals[i]));
comp2D.fill(principal);
}
}
}
}
}
This post has been edited by macosxnerd101: 27 January 2012 - 07:52 PM
Reason for edit:: Renamed title to be more descriptive

New Topic/Question
Reply




MultiQuote









|