Solved

# GUI Mortgage Calculator Part 2

Posted on 2011-05-01
459 Views
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.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;
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);

//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);

//Principal Text Field Features

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

//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);

//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);

// 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);

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

// 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);

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

//Text Area for result

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

// Button for reset button

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

// Button for calculation of the mortgage payments

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

// Action listener to the reset button

public void actionPerformed(ActionEvent e){
onButtonReset();
}
});

//Button Press Calculate

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

}

});

}

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);
}
});
}

}
``````
0

LVL 47

Expert Comment

Well, you just say
textField.getText() - this returns String
which you wil need to parse

double interest= Double.parseDouble(textField.getText());
0

LVL 47

Expert Comment

principal=getDouble(principal_text.getText());

should be

principal=Double.parseDouble(principal_text.getText());
0

LVL 92

Expert Comment

double rate = Double.parseDouble(rate_text.getText());
0

LVL 47

Expert Comment

Well, if you have such method, it may be OK
0

Author Comment

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

LVL 92

Expert Comment

you can use getDouble() actually, your problem is you override whats in the text field with what selected in your combo.
0

Author Comment

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

LVL 47

Expert Comment

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.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;
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);

//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);

//Principal Text Field Features

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

//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);

//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);

// 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);

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

// 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);

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

//Text Area for result

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

// Button for reset button

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

// Button for calculation of the mortgage payments

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

// Action listener to the reset button

public void actionPerformed(ActionEvent e){
onButtonReset();
}
});

//Button Press Calculate

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

}

});

}

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);
}
});
}

}
``````
0

LVL 47

Accepted Solution

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
``````

``````/*
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.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;
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);

//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);

//Principal Text Field Features

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

//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);

//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);

// 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);

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

// 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);

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

//Text Area for result

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

// Button for reset button

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

// Button for calculation of the mortgage payments

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

// Action listener to the reset button

public void actionPerformed(ActionEvent e){
onButtonReset();
}
});

//Button Press Calculate

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

}

});

}

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);
}
});
}

}
``````
0

LVL 92

Expert Comment

> 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

LVL 92

Expert Comment

Let me know if you need help implementing that, its not too hard
0

Author Comment

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

LVL 92

Assisted Solution

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.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;
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);

// 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);

// Principal Text Field Features

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

// 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);

// 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);
public void actionPerformed(ActionEvent event) {
setMortgage();
}
});

// 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);

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

// 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);

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

// Text Area for result

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

// Button for reset button

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

// Button for calculation of the mortgage payments

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

// Action listener to the reset button

public void actionPerformed(ActionEvent e) {
onButtonReset();
}
});

// Button Press Calculate

public void actionPerformed(ActionEvent e) {
calculate();
}

});

}

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
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
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);
}
});
}

}
``````
0

Author Closing Comment

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

### Suggested Solutions

sameEnds challenge 25 55
NotAlone Challenge 20 65
Convert BufferedReader to File 1 49
powerN  challenge 3 34
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…