import javax.swing.JFrame;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.channels.FileChannel;
import static java.lang.Math.min;
/*
PRG/421 Week 3 Assignment: Mortgage Calculator
Author: Jim White
Date: May 9, 2011
Filename: CalcViewer
This is the mortgage loan program
*/
public class CalcViewer {
public static void main(String[] args) {
JFrame frame = new CalcFrame(); //Calls the CalcFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Sets the close operation
//frame.pack();
frame.setVisible(true); //Sets the window to visible
/*The following creates a text file that contains the interest rate and years
I thought it would be best create the file and close the channel before the
program actually started*/
double[] rateyear = new double[6]; // Array to store rateyear
rateyear[0] = 5.35; // Seed the first prime
rateyear[1] = 5.5; // and the second
rateyear[2] = 5.75;
rateyear[3] = 7;
rateyear[4] = 15;
rateyear[5] = 30;
File aFile = new File("interestRates.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile); // Create the file stream
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel file = outputFile.getChannel(); // Get the channel from the stream
final int BUFFERSIZE = (8*rateyear.length); // Byte buffer size
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
DoubleBuffer doubleBuf = buf.asDoubleBuffer(); // View buffer for type double
// Count of rateyear written to file
int rateyearWritten = 0;
while (rateyearWritten < rateyear.length) {
doubleBuf.put(rateyear, // Array to be written
rateyearWritten, // Index of 1st element to write
min(doubleBuf.capacity(), rateyear.length - rateyearWritten));
buf.limit(8*doubleBuf.position()); // Update byte buffer position
try {
file.write(buf);
rateyearWritten += doubleBuf.position();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
doubleBuf.clear();
buf.clear();
}
try {
outputFile.close(); // Close the file and its channel
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import static java.lang.Math.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.DoubleBuffer;
import java.util.Date;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
/*
PRG/421 Week 3 Assignment: Mortgage Calculator
Author: Jim White
Date: May 9, 2011
Filename: CalcFrame
This is the mortgage loan program
*/
public class CalcFrame extends JFrame {//Begining
//Sets up the variables for the fields
private JRadioButton planA;
private JRadioButton planB;
private JRadioButton planC;
private JLabel planLabel;
private JLabel principalLabel;
private JTextField principalField;
private JButton calcButton;
private JButton exitButton;
private JButton clearButton;
private JLabel resultLabel;
private JTextArea resultArea;
private JTextArea graphArea;
private ButtonGroup radioGroup;
private JLabel paymentLabel;
private JTextField paymentField;
private JTextField interestField;
private JLabel interestLabel;
private JTextField yearsField;
private JLabel yearsLabel;
private JLabel graphLabel;
double years;
int months = (int)years*12;
double[] values = new double[months];
private static final int AREA_ROWS = 10;
private static final int AREA_COLUMNS = 30;
public CalcFrame() {//Creates the frame
double payment; //Sets payment variable
this.setTitle("Mortgage Calculator"); //Sets the name of the window
createTextField(); //Creates text field
actionButtons(); //Creates buttons
createPanel(); //Creates panel
//Size and position the window
Toolkit tk = Toolkit.getDefaultToolkit(); //Gets the toolkit and assigns tk as variable
Dimension screenSize = tk.getScreenSize();//Gets the screen size
final int WIDTH = screenSize.width; //Sets the variable WIDTH to screensize width
final int HEIGHT = screenSize.height; //Sets the variable HEIGHT to screensize height
this.setSize(1000, 600); //Set size
this.setLocation(WIDTH/14, HEIGHT/26); //Set position
}
public void createTextField() {
//Creates Objects
//Create buttons
planA = new JRadioButton("7 Years at 5.35%");
planB = new JRadioButton("15 Years at 5.5%");
planC = new JRadioButton("30 Years at 5.75%");
calcButton = new JButton("Calculate");
exitButton = new JButton("Exit");
clearButton = new JButton("Clear");
//Labels
principalLabel = new JLabel("Amount to be Mortgaged: ");
resultLabel = new JLabel("Results: ");
paymentLabel = new JLabel("The payment would be: ");
interestLabel = new JLabel("Interest Rate: ");
yearsLabel = new JLabel("Years to Mortgage: ");
graphLabel = new JLabel("Graphical View: ");
//Text fields
final int FIELD_WIDTH = 10; //field width for text fields
principalField = new JTextField(FIELD_WIDTH);
paymentField = new JTextField(FIELD_WIDTH);
interestField = new JTextField(FIELD_WIDTH);
yearsField = new JTextField(FIELD_WIDTH);
paymentField.setForeground(Color.blue);
paymentField.setEditable(false);
resultArea = new JTextArea();
resultArea.setEditable(false);
}
private void createPanel() { //Adds components to the panel and adds the panel
//Border
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
BevelBorder bEdge = new BevelBorder(BevelBorder.RAISED);
//Add elements to the top box
Box top = Box.createHorizontalBox();
top.add(Box.createHorizontalStrut(10));
top.add(Box.createVerticalStrut(25));
top.add(principalLabel);
top.add(principalField);
top.add(Box.createHorizontalStrut(10));
top.add(interestLabel);
top.add(interestField);
top.add(Box.createHorizontalStrut(10));
top.add(yearsLabel);
top.add(yearsField);
top.add(Box.createHorizontalStrut(10));
top.add(paymentLabel);
top.add(paymentField);
top.setBorder(bEdge);
top.setBackground(Color.BLACK);
//Add elements to the center box
Box center = Box.createVerticalBox();
//center.add(Box.createHorizontalStrut(20));
center.add(Box.createVerticalStrut(10));
center.add(resultLabel);
center.add(Box.createRigidArea(new Dimension(0,5)));
JScrollPane scrollPane = new JScrollPane(resultArea);
center.add(scrollPane);
center.add(Box.createRigidArea(new Dimension(0,5)));
center.add(graphLabel);
GraphView graph = new GraphView();
JScrollPane graphPane = new JScrollPane(graph);
center.add(graphPane);
graphPane.setBorder(edge);
center.setBorder(bEdge);
graph.setValues(values);
center.setBackground(Color.black);
//Add elements to the bottom box
JPanel bottom = new JPanel();
Dimension bSize = new Dimension(100, 40);
bottom.add(Box.createHorizontalStrut(20));
bottom.add(calcButton);
calcButton.setBorder(edge);
calcButton.setPreferredSize(bSize);
bottom.add(Box.createHorizontalStrut(20));
bottom.add(clearButton);
clearButton.setBorder(edge);
clearButton.setPreferredSize(bSize);
bottom.add(Box.createHorizontalStrut(20));
bottom.add(exitButton);
exitButton.setBorder(edge);
exitButton.setPreferredSize(bSize);
bottom.setBorder(bEdge);
bottom.setBackground(Color.cyan);
//Add elements to the left box
Box left = Box.createVerticalBox();
radioGroup = new ButtonGroup();
left.add(Box.createVerticalStrut(70));
left.add(planLabel = new JLabel("Select Option Below: "));
left.add(Box.createVerticalStrut(10));
radioGroup.add(planA);
left.add(planA);
radioGroup.add(planB);
left.add(planB);
radioGroup.add(planC);
left.add(planC);
left.setBorder(bEdge);
left.setBackground(Color.BLACK);
//Cursors
Cursor textCur = top.getCursor();
Cursor handCur = left.getCursor();
top.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
left.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
//Add panels to content pane
Container content = this.getContentPane();
content.setLayout(new BorderLayout());
content.add(center, BorderLayout.CENTER);
content.add(top, BorderLayout.NORTH);
content.add(bottom, BorderLayout.SOUTH);
content.add(left, BorderLayout.WEST);
}
private void actionButtons() { //Create void for actions on elements
class buttonListener implements ActionListener { //Add action listener
public void actionPerformed(ActionEvent event) {
//The following retrieves the rates from the interestrates file
File aFile = new File("interestRates.txt");
FileInputStream inFile = null;
try { //Try catch for file not found, it must exist
inFile = new FileInputStream(aFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inFile.getChannel();
final int RATECOUNT = 6; //Number of elements to extract from the file
ByteBuffer buf = ByteBuffer.allocate(8*RATECOUNT);//Sets the buffer up for double
double[] rates = new double[RATECOUNT];
try {
int ratesRead = 0;
while(inChannel.read(buf) != -1) {
DoubleBuffer doubleBuf = ((ByteBuffer)(buf.flip())).asDoubleBuffer();//Sets up the buffer
ratesRead = doubleBuf.remaining();
doubleBuf.get(rates, 0, doubleBuf.remaining());
for(int i = 0; i < ratesRead; i++) { //gets the rates and years
}
aFile.deleteOnExit(); //Delets the interestRates text file when the program exits
buf.clear(); // Clear the buffer for the next read
}
inFile.close(); // Close the file and the channel
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
//Array for mortgage calculator
double[][] mortgage = new double [2][3]; //creates two arays with three elements each
mortgage[0][0] = rates[0]; //Values set to array elements
mortgage[0][1] = rates[1]; //extracted from the text file
mortgage[0][2] = rates[2];
mortgage[1][0] = rates[3];
mortgage[1][1] = rates[4];
mortgage[1][2] = rates[5];
//Sets command as variable and assigns action
Object command = event.getSource();
if (command == calcButton) {
try {
Double.parseDouble(interestField.getText());
Double.parseDouble(yearsField.getText());
}
catch (Exception e) {
resultArea.setForeground(Color.red); //Sets output for exception font color to red
Font eFont = new Font("Times New Roman", Font.BOLD, 24); //Sets the font for the exception message
resultArea.setFont(eFont);
resultArea.setText(" "+e.getMessage()+
" is not a numeric value. \n Please re-enter a numeric value in the field "+
"\n and try again.");
return;
}
//Sets the variables for the calcButton
double calcInt = Double.parseDouble(interestField.getText());
double calcYears = Double.parseDouble(yearsField.getText());
//Calls the mortgageCalc method and assigns variables
mortgageCalc (calcInt, calcYears);
}
else if(command == exitButton) {
System.exit(0);
}
else if(command == clearButton) {
principalField.setText("");
resultArea.setText("");
paymentField.setText("");
interestField.setText("");
yearsField.setText("");
radioGroup.clearSelection();
}
else if(command == planA) {
mortgageCalc(mortgage[0][0], mortgage[1][0]);//Calls the mortgageCalc method and assigns variables
}
else if(command == planB) {
mortgageCalc(mortgage[0][1], mortgage[1][1]);//Calls the mortgageCalc method and assigns variables
}
else if(command == planC) {
mortgageCalc(mortgage[0][2], mortgage[1][2]);//Calls the mortgageCalc method and assigns variables
}
}//End action event
}//End listener
//Attaches the listeners
ActionListener listener = new buttonListener();
calcButton.addActionListener(listener);
exitButton.addActionListener(listener);
clearButton.addActionListener(listener);
planA.addActionListener(listener);
planB.addActionListener(listener);
planC.addActionListener(listener);
}//End actionButtons
private void mortgageCalc(double interest, double years) {
//Try/catch for input
try {
Double.parseDouble(principalField.getText());
}
catch (Exception e) {
resultArea.setForeground(Color.red); //Sets output for exception font color to red
Font eFont = new Font("Times New Roman", Font.BOLD, 24); //Sets the font for the exception message
resultArea.setFont(eFont);
resultArea.setText(" "+e.getMessage()+
" is not a numeric value. \n Please enter a numeric value in the 'Amount to be Mortgaged:' field "+
"\n and try again.");
return;
}
double principal = Double.parseDouble(principalField.getText()); //Principal to be mortgaged
double MI = interest/100/12; //Sets the interest up for the mortgage formula
double payment = 0; //Sets the payment to zero
double months = years * 12; //Converts the years to months
double balance = principal; //Sets the balance due = principalo
int paymentNumber = 1; //Sets initial payment number
//display only two decimal places and a comma seperator
java.text.DecimalFormat dec = new java.text.DecimalFormat("$###,##0.00"); //Set the decimal format
//Mortgage payment formula
//P = L[c(1 + c)n]/[(1 + c)n - 1]
payment = ((principal*MI)/(1-((pow(1 + MI, -months)))));
//This outputs the principal, years of payments, interest rate, and the payment
paymentField.setText(" "+dec.format(payment));
//Headers for columns
String header = "\n\n\n\tPayment \tMonthly \tPrincipal \tInterest \tLoan\n "+
"\tNumber\tPayment \tPaid \tPaid \tBalance\n "+
"\t---------\t----------\t-----------\t---------\t------------\n";
resultArea.setForeground(Color.black); //Sets font color to black
Font font = new Font("Serif", Font.PLAIN, 14); //Sets the font for the result area
resultArea.setFont(font);
resultArea.append(header); //Prints header
//Begins the while loop for the payments
while (paymentNumber <= months){
//Loan balance after n payments have been made and sets the variables
double monthlyIP=(balance*MI);
double monthlyPP=(payment-monthlyIP);
balance = balance-monthlyPP;
//Prints the payment #, payment, interest paid, principal paid, and balance
resultArea.append("\t"+(int)paymentNumber+"\t" + dec.format(payment)+"\t "+dec.format(monthlyIP)+"\t "
+dec.format(monthlyPP)+ "\t" +dec.format(balance)+"\n");
paymentNumber++;
}// end while
}//End Mortgage calc
}//End
import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
/**
* Sample program to show off the GraphCanvas
*/
public class GraphView extends JPanel
{
GraphCanvas graph = new GraphCanvas();
public GraphView()
{
setLayout(new BorderLayout());
setSize(200, 200);
add(graph, BorderLayout.CENTER);
}
public void setValues(double[] values) {
graph.setValues(values);
}
public class CoordCanvas extends Canvas
{
protected double viewLeft;
protected double viewRight;
protected double viewTop;
protected double viewBottom;
public void setXRange(double left, double right)
{
viewLeft = left;
viewRight = right;
}
public void setYRange(double top, double bottom)
{
viewTop = top;
viewBottom = bottom;
}
public double toX(double x)
{
return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
}
public double toY(double y)
{
return (y - viewTop) * getSize().height / (viewBottom - viewTop);
}
public double toWidth(double w)
{
return w * getSize().width / Math.abs(viewRight - viewLeft);
}
public double toHeight(double h)
{
return h * getSize().height / Math.abs(viewBottom - viewTop);
}
}
/** Sample CoordCanvas subclass to draw a bar graph
*/
class GraphCanvas extends 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, (double)vals.length);
this.setYRange((double)max, 0F);
// draw the graph
Graphics2D comp2D = (Graphics2D)comp;
for (int i = 0; i < vals.length; i++)
{
Rectangle2D.Double remainingPrincipal = new Rectangle2D.Double(toX((double)i),
toY((double)vals[i]), toWidth(1F), toHeight((double)vals[i]));
comp2D.fill(remainingPrincipal);
}
}
}
}
This it what I have.

New Topic/Question
Reply




MultiQuote





|