Solved

# Mortgage calculator - How do I make controls unavailable based on radio button

Posted on 2006-06-18
297 Views
Hi,
I have posted my mortgage calculator below. Everything seems to work fine. The calculator lets you select a radio button to determine if you want to select pre-determined loans or enter your own parameters. This works fine, but I would like to make the predefined radio buttons unavailable if the user selects user parameters, and the user parameters unavailable if the user selects pre-defined loans. I would also like to dim the unavailable one if that is possible.
Any assistance would be appreciated.
Thanks,
Jon

//week3 Jan Scha

/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 10,2006
Filename:    Mortgage.java
Purpose:     This project accepts the mortgage amountand allows  the user to select one of 3
pre-determined loans.The program then calculates the monthly mortgage payment and displays
it in currency format. The program then displays the payment number, the monthly principle
paid, the monthly interest paid, and the current loan balance.There is a quit button to
exit the application, and a clear button to clear user entered fields as well as the amortization table.
in order to calculate a new mortgage. The program will also clear the payment field should
the user press any key while positioned in the input textfield for amount.

*/

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JScrollPane.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.*;
import java.text.DecimalFormat;

class Mortgage extends JFrame
{

//Program variables

double yearlyRate[] =
{
// array of interest rates
5.35, 5.50, 5.75
};
int term[] =
{
//array of terms
7, 15, 30
};
int termMonths[] =
{
//array of terms in months
84, 180, 360
};

int payment = 0; // payment counter
int i = 0; // used as index
// initialize variable for monthly interest rate
double monthlyInterest = 0.00;
double principle = 0.00;
// initialize mothly principle paid field
double monthlyPrinciplePaid = 0.00;
double interestRateMonthly = 0.00;
double monthlyPayment;
int amount = 0;
double yearinRate = 0.00;
int termin = 0;
int monthCount = 0;

Border rowborder = new EmptyBorder(3, 10, 3, 10);
// Format output
DecimalFormat currency = new DecimalFormat("\$0.00");

// JLabel and JTextField for the mortgage amount
private JLabel amountJLabel;
private JTextField amountJTextField;

// JLabel for monthly mortgage payment
private JLabel monthpayJLabel;

// JTextArea for displaying payment
private JTextArea outputJTextArea;

// Label for asking user choice
private JLabel choiceJLabel;

// JButton to initiate calculations
private JButton calculateJButton;

// JButton to display amortization table
private JButton displayJButton;

// JButton to clear entries
private JButton clearJButton;

// JButton to quit
private JButton quitJButton;

// JLabel and JTextField for interest percentage rate
private JLabel interestJLabel;
private JTextField interestJTextField;

// JLabel and JTextField for mortgage term
private JLabel termJLabel;
private JTextField termJTextField;

// Create radio panel for pre-determined loans

JTextArea displayArea = new JTextArea(10, 75);
JScrollPane scroll = new JScrollPane(displayArea);

// Create radio panel for method choice
JPanel choicePanel = new JPanel();

// no-argument constructor
public Mortgage()

{
createUserInterface();
}

// create and position the GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();

setTitle("Mortgage Calculator"); // set title bar text

// enable specific positioning of GUI components
contentPane.setLayout(null);

// set up amountJLabel
amountJLabel = new JLabel();
amountJLabel.setBounds(76, 5, 104, 26); // set size and position
amountJLabel.setText("Mortgage amount:");

// set up choiceJLabel
choiceJLabel = new JLabel();
choiceJLabel.setBounds(166, 50, 104, 26); // set size and position
choiceJLabel.setText("Select a method");

// set up amountJTextField
amountJTextField = new JTextField();
amountJTextField.setBounds(200, 5, 56, 26); // set size and position
amountJTextField.setHorizontalAlignment(JTextField.RIGHT);

new KeyAdapter() // anonymous inner class
{
// event handler for key pressed in amountJTextField
public void keyPressed(KeyEvent event)
{
amountJTextFieldkeyPressed(event);
}

} // end anonymous inner class

); // end call to addKeyListener

// set up interestJLabel
interestJLabel = new JLabel("Annual interest rate:");
interestJLabel.setBounds(226, 170, 115, 26);
interestJLabel.setText("Annual interest rate:");

// set up interestJTextField
interestJTextField = new JTextField();
interestJTextField.setBounds(370, 170, 56, 26);
interestJTextField.setHorizontalAlignment(JTextField.RIGHT);

new KeyAdapter() // anonymous inner class
{
// evend handler for key pressed in interestJTextField
public void keyPressed(KeyEvent event)
{
interestJTextFieldkeyPressed(event);
}

} // end anonymous inner class

); // end call to addKeyListener

// set up termJLabel for term of loan
termJLabel = new JLabel();
termJLabel.setBounds(226, 130, 140, 26);
termJLabel.setText("Mortgage length (Years):");

// set up termJTextField to receive term of loan
termJTextField = new JTextField();
termJTextField.setBounds(370, 130, 56, 26);
termJTextField.setHorizontalAlignment(JTextField.RIGHT);

new KeyAdapter() // anonymous inner class
{
// event handler for key pressed in termJTextField
public void keyPressed(KeyEvent event)
{
termJTextFieldkeyPressed(event);
}

} // end anonymous inner class

); // end call to addKeyListener

ButtonGroup bgroup = new ButtonGroup();
radioPanel.setBounds(30, 120, 195, 95); // set size and position

ButtonGroup choicegroup = new ButtonGroup();
choicePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
choicePanel.setBorder(rowborder);
//choicePanel.setBounds(130, 225, 195, 95); // set size and position
choicePanel.setBounds(29, 75, 500, 95);

// set up calculateJButton
calculateJButton = new JButton();
calculateJButton.setBounds(26, 220, 90, 26); // set size and position
calculateJButton.setText("Calculate");

new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event)
{

calculateJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up displayJButton
displayJButton = new JButton();
displayJButton.setBounds(26, 280, 200, 26); // set size and position
displayJButton.setText("Display Amortization Table");

new ActionListener() // anonymous inner class
{
// event handler called when clearJButton is pressed
public void actionPerformed(ActionEvent event)
{
displayJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up clearJButton
clearJButton = new JButton();
clearJButton.setBounds(120, 430, 90, 26); // set size and position
clearJButton.setText("Clear");

new ActionListener() // anonymous inner class
{
// event handler called when clearJButton is pressed
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up quitJButton
quitJButton = new JButton();
quitJButton.setBounds(270, 430, 90, 26); // set size and position
quitJButton.setText("Quit");

new ActionListener() // anonymous inner class
{
// event handler called when quitJButton is pressed
public void actionPerformed(ActionEvent event)
{
quitJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up outputJTextArea
outputJTextArea = new JTextArea();
outputJTextArea.setBounds(300, 220, 56, 26); // set size and position
outputJTextArea.setEditable(false);

//set up monthpayJLabel
monthpayJLabel = new JLabel();
monthpayJLabel.setBounds(176, 220, 156, 26); // set size and position
monthpayJLabel.setText("Monthly Payment:");

scroll.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
scroll.setBounds(20, 300, 440, 130); // set size and position
setVisible(true);

} // end method createUserInterface

// called when user presses key in amountJTextField
private void amountJTextFieldkeyPressed(KeyEvent event)
{
outputJTextArea.setText(""); // clear outputJTextArea
displayArea.setText(""); // clear display
payment = 0; // reset payment counter
}

// method called when user clicks calculateJButton
private void calculateJButtonActionPerformed(ActionEvent event)
{
try
{
// check which radio buttonis selected and set index
if (aButton.isSelected())
{
i = 0;
}

if (bButton.isSelected())
{
i = 1;
}

if (cButton.isSelected())
{
i = 2;
}

// check which radio buttonis selected and set index
if (predefButton.isSelected())
{
interestRateMonthly = (yearlyRate[i] / 12) / 100;
monthCount = (term[i] * 12);
}

if (entryButton.isSelected())
{
yearinRate = Double.parseDouble(interestJTextField.getText());
termin = Integer.parseInt(termJTextField.getText());
interestRateMonthly = (yearinRate / 12) / 100;
monthCount = (termin * 12);
}

//define display area titles
String titles = "Month \t Principal\t Interest\tBalance\n";
//put titles in display area
displayArea.setText(titles);
// initialize loan balance field
double loanbalance = 0.00;

// initialize payment counter

// clear outputJTextArea
outputJTextArea.setText("");
// clear display area
displayArea.setText("");
// Calculate months from years

// get mortgage amount
amount = Integer.parseInt(amountJTextField.getText());
//create variable to store decreasing principle
principle = amount;
// Calculate monthly interest

// Calculate monthly payment
monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1 +
interestRateMonthly,  - monthCount));

// Output payment amount
outputJTextArea.setText(currency.format(monthlyPayment));

}

catch (NumberFormatException ex){}
}

// method called when user clicks clearJButton
private void clearJButtonActionPerformed(ActionEvent event)
{
try
{

monthlyPrinciplePaid = 0.00;
outputJTextArea.setText(""); // clear outputJTextArea
amountJTextField.setText(""); // clear amountJTextField
displayArea.setText(""); // clear display area
termJTextField.setText(""); // clear term text box area
interestJTextField.setText(""); // clear term text box area
payment = 0; // reset payment counter

}
catch (NumberFormatException ex){}
}

// method called when user clicks displayJButton
private void displayJButtonActionPerformed(ActionEvent event)
{
try
{

// reset values in case user presses display more than once
principle = Integer.parseInt(amountJTextField.getText());
monthlyPrinciplePaid = 0.00;
displayArea.setText(""); // clear display
payment = 0;
monthlyPrinciplePaid = 0.00;

//define display area titles
String titles = "Month \t Principal\t Interest\tBalance\n";
//put titles in display area
displayArea.setText(titles);
// initialize loan balance field

// loop for creating amortization table
for (int a = 0; a < monthCount; a = a + 1)
{
//increment payment counter
payment++;
// calculate monthly interest
monthlyInterest = principle * interestRateMonthly;
// calculate monthly principle
monthlyPrinciplePaid = monthlyPayment - monthlyInterest; //
//save declining balance
principle = principle - monthlyPrinciplePaid;

// display amortization table
displayArea.append(payment + "\t" + currency.format
(monthlyPrinciplePaid) + "\t" + currency.format
(monthlyInterest) + "\t" + currency.format(Math.abs
(principle)) + "\n");
displayArea.setCaretPosition(0);

}
}

catch (NumberFormatException ex){}
}

// method called when user clicks quitJButton
private void quitJButtonActionPerformed(ActionEvent event)
{
try
{
System.exit(0);

}
catch (NumberFormatException ex){}
}

// called when user presses key in termJTextField
private void termJTextFieldkeyPressed(KeyEvent event)
{
outputJTextArea.setText(""); // clear outputJTextArea
}

// called when user presses key in interestJTextField
private void interestJTextFieldkeyPressed(KeyEvent event)
{
outputJTextArea.setText(""); // clear outputJTextArea
}

// main method
public static void main(String[]args)
{
Mortgage application = new Mortgage();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(480, 500);
application.setVisible(true);
} // end method main

} // end class Mortgage
0
Question by:ghost8067
• 3

LVL 9

Expert Comment

ID: 16929242
U need to implement ActionListener
and tell the program that when u click on, for example, predefButton,
u want to execute instrructions to disable the buttons of the user defined functions.

class Mortgage extends JFrame implements ActionListener
{
[...]

ButtonGroup choicegroup = new ButtonGroup();
[...]
// Initially the predefined is selected so disable the user defined functions
termJTextField.setEnabled(false);
interestJTextField.setEnabled(false);
[...]
public void actionPerformed(ActionEvent e) {
// if predefButton is selected, disable user defined functions
if(e.getSource() == predefButton) {
aButton.setEnabled(true);
bButton.setEnabled(true);
cButton.setEnabled(true);
termJTextField.setEnabled(false);
interestJTextField.setEnabled(false);
}
// if entryButton is selected, disable pre-defined functions
else if(e.getSource() == entryButton) {
termJTextField.setEnabled(true);
interestJTextField.setEnabled(true);
aButton.setEnabled(false);
bButton.setEnabled(false);
cButton.setEnabled(false);
}
}
0

LVL 9

Expert Comment

ID: 16929254
I resume :

1)
u need to tell the class that it listens to actions. (implements ActionListener)

2)
tell which component send actions to the class
So in this case, we registered predefButton and entryButton.
)

3)
code the function actionPerformed, it's the method invoked when an action is fired from a registered component
(in this case predefButton, entryButton)

In this method u need to check wich component fired action
if(e.getSource() == ...
0

Author Comment

ID: 16929403
Matthew,
Thanks for gowing my knowledge. It is working well. I have one additional question.( I am not sure if I'm supposed to do this. If it is not correct etiquette please let me know.) The labels on the radio button dim when disabled. Is there a way I can dim the labels for my text boxes on my user entries when disabled?
Jon
0

LVL 9

Accepted Solution

matthew016 earned 500 total points
ID: 16929580
Yes, u can use setEnabled like i showed u for the radiobuttons and textfields,

so u get
[...]
termJTextField.setEnabled(false);
interestJTextField.setEnabled(false);
termJLabel.setEnabled(false);
interestJLabel.setEnabled(false);
[...]
public void actionPerformed(ActionEvent e) {
if(e.getSource() == predefButton) {
aButton.setEnabled(true);
bButton.setEnabled(true);
cButton.setEnabled(true);
termJLabel.setEnabled(false);
interestJLabel.setEnabled(false);
termJTextField.setEnabled(false);
interestJTextField.setEnabled(false);
}
else if(e.getSource() == entryButton) {
termJTextField.setEnabled(true);
interestJTextField.setEnabled(true);
termJLabel.setEnabled(true);
interestJLabel.setEnabled(true);
aButton.setEnabled(false);
bButton.setEnabled(false);
cButton.setEnabled(false);
}
}

If I were u I 'd create a method :
public void setEnabledUserDefinedFct(boolean bool) {
termJTextField.setEnabled(bool);
interestJTextField.setEnabled(bool);
termJLabel.setEnabled(bool);
interestJLabel.setEnabled(bool);
}
and same thing for predefined fields :
public void setEnabledPreDefinedFct(boolean bool) {
aButton.setEnabled(bool);
bButton.setEnabled(bool);
cButton.setEnabled(bool);
}
then u call these two methods.

[...]
setEnabledUserDefinedFct(false);
[...]
public void actionPerformed(ActionEvent e) {
if(e.getSource() == predefButton) {
setEnabledPreDefinedFct(true);
setEnabledUserDefinedFct(false);
}
else if(e.getSource() == entryButton) {
setEnabledUserDefinedFct(true);
setEnabledPreDefinedFct(false);
}
}

It's better to use functions because if u decide to add another field and disable/enable it when selecting one of the radiobuttons,
u just need to add one line in the appropriate function, and not three lines if we didnt have the function.
0

## Featured Post

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…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …