1 Replies - 462 Views - Last Post: 09 October 2011 - 11:28 PM Rate Topic: ***** 1 Votes

#1 padmeskywalker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-August 11

Mortgage Calculator GUI

Posted 09 October 2011 - 05:03 PM

Getting stuck on a particular part. I have the following rubric:

Write the program in Java (with a graphical user interface) so that it will allow the user to select which way they want to calculate a mortgage: by input of the amount of the mortgage, the term of the mortgage, and the interest rate of the mortgage payment or by input of the amount of a mortgage and then select from a menu of mortgage loans:

- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%

In either case, display the mortgage payment amount and then, list the loan balance and interest paid for each payment over the term of the loan. Allow the user to loop back and enter a new amount and make a new selection, or quit. Insert comments in the program to document the program.


I have the following code which works for the menu of terms and interest rate selections (- 7 year at 5.35%
- 15 year at 5.5 % - 30 year at 5.75%). However, I can't figure out how to implement another GUI option which would allow them to "select which way they want to calculate a mortgage: by input of the amount of the mortgage, the term of the mortgage, and the interest rate of the mortgage payment". Please help me understand how to augment this GUI to offer the other options, I'm really lost.


Partial code listed below:



//List of Import Library
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.text.DecimalFormat;



//Declaration of Public Class and Action Listener
public class Week3 extends JFrame implements ActionListener { 
    

//Variable Declarations
double intPrinciple, interestRate, calcPayment, monthlyInterest, currentInterest, principlePaid, newBalance;
int termYears, termMonths, done, i=0, m=0, p=0;
double interestOptionArray[] = {5.75, 5.5, 5.35};
int termOptionArray[] = {30, 15, 7};
String principle;
String optionArray[] = {"30 Year Term at 5.75%", "15 Years at 5.5%", "7 Year Term at 5.35%"};


//Declaration of Panel Imports        
JPanel topPanel = new JPanel();


//Decimal Formatting
DecimalFormat twoDigits = new DecimalFormat("$ #,###,###,###.00");


//Imports of GUI Panels and Labels
 JPanel inputPanel = new JPanel();
 JLabel intPrincipleLabel = new JLabel("Amount of Principle:");
 JTextField intPrincipleField = new JTextField(10); //Length of Principle Field
 JLabel loanOptionLabel = new JLabel("Term in Years & Interest Rates:");
 JComboBox loanOptionBox = new JComboBox(); //Scroll Box for Term/Interest
 JLabel monthlyPaymentLabel = new JLabel("Calculated Mortgage:");
 JLabel monthlyPaymentField = new JLabel(""); //Field for Calculated Mortgage
 JPanel buttonPanel = new JPanel(); //Horizontal GUI
 JButton calcPaymentBtn = new JButton("Calculate Payments");
 JButton displayMoreBtn = new JButton("Display More");
 JButton clearFieldsBtn = new JButton("Clear Fields");
 JButton finishBtn = new JButton("Finish"); //Output Field and Exit
 JTextPane displayPane = new JTextPane();
 JPanel messagePanel = new JPanel();
 JLabel messageLabel = new JLabel("McBride Financial Mortgage Calculator:"); //Title

 
//Declaration of Public Class for Mortgage Arrays      
         
public Week3 () {

    
 //Arrays
 loanOptionBox.addItem(optionArray[0]);
 loanOptionBox.addItem(optionArray[1]);
 loanOptionBox.addItem(optionArray[2]);
 loanOptionBox.addActionListener(this);
 
 
 
//Graphical Representation of Text
JPanel displayPanel = new JPanel();
setTabsAndStyles(displayPane);
displayPane = addTexttoTextPane();
JScrollPane scrollPane = new JScrollPane(displayPane, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new Dimension(400, 300));
displayPane.setEditable(false);
displayPanel.add(scrollPane);


//Panel Layouts, Spacing, and Fields
Container c = getContentPane();
c.setLayout(new BorderLayout());
topPanel.setLayout(new BorderLayout());
messagePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
inputPanel.setLayout(new GridLayout(3, 2));
buttonPanel.setLayout(new FlowLayout());
displayPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
topPanel.add(messagePanel, BorderLayout.NORTH);
topPanel.add(inputPanel, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
messagePanel.add(messageLabel);
inputPanel.add(intPrincipleLabel);
inputPanel.add(intPrincipleField);
inputPanel.add(loanOptionLabel);
inputPanel.add(loanOptionBox);
inputPanel.add(monthlyPaymentLabel);
inputPanel.add(monthlyPaymentField);


//GUI Buttons on Display Box
 buttonPanel.add(calcPaymentBtn); //Calculate Payment Button
 buttonPanel.add(displayMoreBtn); //Display More Button
 buttonPanel.add(clearFieldsBtn); //Clear Fields Button
 buttonPanel.add(finishBtn); //Finish Button
        
 
//Panel Layout Configuration
c.add(topPanel, BorderLayout.NORTH);
c.add(displayPanel, BorderLayout.CENTER);


//Event Handlers for GUI Button Input
calcPaymentBtn.addActionListener(this);
displayMoreBtn.addActionListener(this);
clearFieldsBtn.addActionListener(this);
finishBtn.addActionListener(this);
}

        
//Array Arguments
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if (e.getSource() == loanOptionBox) {
switch (loanOptionBox.getSelectedIndex()) {
case 0:
i = 0;
break;
case 1:
i = 1;
break;
case 2:
i = 2;
break;
}
}

                
//Disposition and Conditions for Calculate Payments Input
if (    "Calculate Payments".equals(arg)) {
monthlyPaymentField.setText("");
principle = intPrincipleField.getText();
try {
intPrinciple = Double.parseDouble(principle);
if (intPrinciple <= 0) throw new NumberFormatException();
}
catch(NumberFormatException n){
done = 1;
}
if (done == 1)
done = 0;
else {
interestRate = interestOptionArray[i];
termYears = termOptionArray[i];
monthlyInterest = interestRate/(12*100); //Monthly Interest Formula
termMonths = termYears*12; //Formula for Number of Total Months
calcPayment = monthlyInterest*intPrinciple/(1-Math.pow((1+monthlyInterest), -termMonths)); //Mortgage Payment Formula
monthlyPaymentField.setText(" " + twoDigits.format(calcPayment));
m = 0;
try {
Document doc = displayPane.getDocument();
doc.remove(0, doc.getLength());
doc.insertString(0, "Month # \tPrinciple \tInterest \tRemaining \n", displayPane.getStyle("medium"));
}
catch(BadLocationException ble) {
System.err.println("Input Error");
}       
for (m=0; m<=11; m++) {
currentInterest = intPrinciple * monthlyInterest;
principlePaid = calcPayment - currentInterest;
newBalance = intPrinciple - principlePaid;
intPrinciple = newBalance;
try {
Document doc = displayPane.getDocument();
doc.insertString(doc.getLength(), (m+1) + "\t", displayPane.getStyle("bold"));
doc.insertString(doc.getLength(), twoDigits.format(principlePaid) + "\t", displayPane.getStyle("regular"));
doc.insertString(doc.getLength(), twoDigits.format(currentInterest) + "\t", displayPane.getStyle("regular"));
doc.insertString(doc.getLength(), twoDigits.format(newBalance) + "\n", displayPane.getStyle("regular"));
}
catch(BadLocationException ble) {
System.err.println("Input Error");
}                                       
}
}
}

//Disposition and Conditions for Display More Option

if (    "Display More".equals(arg)) {
if (calcPayment == 0) {
monthlyPaymentField.setText("Please Enter Principle");
}
else if (m == termMonths) {
try {
Document doc = displayPane.getDocument();
doc.remove(0, doc.getLength());
doc.insertString(0, "No Balance Remaining", displayPane.getStyle("bold"));
}
catch(BadLocationException ble) {
System.err.println("Input Error");
}
}
else {
try {
Document doc = displayPane.getDocument();
doc.remove(0, doc.getLength());
doc.insertString(0, "Month # \tPrinciple \tInterest \tRemaining \n", displayPane.getStyle("medium"));
}
catch(BadLocationException ble) {
System.err.println("Input Error");
}       
for (p=0; p<=11; p++) {
newBalance = intPrinciple - principlePaid;
currentInterest = intPrinciple * monthlyInterest;
intPrinciple = newBalance;
try {
Document doc = displayPane.getDocument();
doc.insertString(doc.getLength(), (m+1) + "\t", displayPane.getStyle("bold"));
doc.insertString(doc.getLength(), twoDigits.format(principlePaid) + "\t", displayPane.getStyle("regular"));
doc.insertString(doc.getLength(), twoDigits.format(currentInterest) + "\t", displayPane.getStyle("regular"));
doc.insertString(doc.getLength(), twoDigits.format(newBalance) + "\n", displayPane.getStyle("regular"));        
m++;
}
catch(BadLocationException ble) {
System.err.println("Input Error");
}
}
p = 0;
}
}
       

//Disposition and Conditions for Clear Fields Option
                
 if (arg == "Clear Fields") {
 intPrincipleField.setText("");
 loanOptionBox.setSelectedIndex(0);
 monthlyPaymentField.setText("");
 displayPane.setText("");
 calcPayment = 0;
 }
 
 
//Disposition and Conditions for Finish Option
if (arg == "Finish")
System.exit(0);
}
        
//Tab Formatting Declarations
protected void setTabsAndStyles(JTextPane displayPane) { //creates tabs and styles
TabStop[] tabs = new TabStop[3];
tabs[0] = new TabStop(100, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[2] = new TabStop(300, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset = tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
displayPane.setParagraphAttributes(aset, false);
       

//Font Formatting Declarations
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = displayPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "TimesNewRoman");
Style s = displayPane.addStyle("italic", regular);   
StyleConstants.setItalic(s, true);
s = displayPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);
s = displayPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 14);
}
        
public JTextPane addTexttoTextPane() {
Document doc = displayPane.getDocument();
return displayPane;
}
 
//Exit and GUI Frame Declarations
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
Week3 f = new Week3();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 450);
f.setVisible(true);
f.setTitle("SR-mf-003, Change Request 5"); //Bar header
} 
}




This post has been edited by macosxnerd101: 09 October 2011 - 05:20 PM
Reason for edit:: Renamed title to be more descriptive


Is This A Good Question/Topic? 0
  • +

Replies To: Mortgage Calculator GUI

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4333
  • View blog
  • Posts: 12,128
  • Joined: 18-April 07

Re: Mortgage Calculator GUI

Posted 09 October 2011 - 11:28 PM

You can use a radio button group. That way the user can select which radio button choice (and only one choice) they would like. Then when it comes to calculating the mortgage, you read the radio buttons to see which is selected and create the appropriate formula.

// Create a radio button
JRadioButton byInputOfMortgage = new JRadioButton("Input of Mortgage");

// Create a group of radio buttons
ButtonGroup buttonGroup = new ButtonGroup( );

// Add button to group
buttonGroup.Add(byInputofMortgage);

// In some action event (like a button click)
if (byInputOfMortgage.isSelected()) {
   // Do formula code here based on input of mortgage
}



So the first three lines above show you how to create a radio button and add it to a group. The last if statement would show you how to check if the radio button was selected. If it is selected, you then create the appropriate formula.

:)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1