How to get JTextArea text from another method - java

I want to use method from another class to append in my JTextArea (TEXT IS HERE in my code), how to do it?
SecondWindow() {
super("Mortage Loan Calculator");
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
tArea = new JTextArea(***TEXT IS HERE***, 30, 40);
scroll = new JScrollPane(tArea);
add(scroll);
setLocationRelativeTo(null);`
`And here is a method:
public void calcAnnuity(int years, int months, double amount, double rate){
double totalMonths = (12 * years) + months;
double partOfRate = rate / 12.0 / 100.0;
double tempAmount = amount;
double payment = amount * partOfRate * Math.pow(1 + partOfRate, totalMonths) / (Math.pow(1 + partOfRate, totalMonths) - 1); //mathematical formula
DecimalFormat decFormat = new DecimalFormat("#.##");
System.out.println(1 + " Payment = " + decFormat.format(payment) + "--- Left to pay: " + decFormat.format(amount));
for(int i = 2; i <= totalMonths; i++) {
tempAmount -= (payment - partOfRate * amount);
amount -= payment;
**textishere.append**(i + " Payment = " + decFormat.format(payment) + " --- Left to pay: " + decFormat.format(tempAmount));
}
}

Well, the easiest way would be to implement a public static method in your ClassA where the JTextArea is located.
public static setJTextAreaText(String text){
tArea.setText(text);
}
And in your ClassB you import ClassA and then call this method from your method calcAnnuity()
import ClassA;
public void calcAnnuity(int years, int months, double amount, double rate){
...
ClassA.setJTextAreaText('**textishere.append**');
}

Related

Why is my change calculator not working for coins?

I'm trying to make a program that calculates tax and what change needs to be given back, but for some reason, it doesn't tell me what coins to give back. The code tells me which bills I would need to give back, but the coins that are in the decimals don't work. I've tried looking all over stack exchange for a solution, but if I'm being honest, I'm not really sure what to even look for in the first place, so I haven't found a solution. I'm also new to Java and text-based coding in general, so any feedback is appreciated!
Here is my code:
import java.util.*;
public class Decisions1 {
static String taskValue = "C1";
public static void main(String[] args) {
//initiates the scanner
Scanner myInput = new Scanner(System.in);
//creates the variables for the total
double total1 = 0;
//asks for the total cost of all goods
System.out.println("Please enter the total cost of all goods. This program will add tax and calculate the change you must give back to the customer.");
total1 = myInput.nextDouble();
//performs calculations for tax
double tax2 = (total1*1.13);
double tax1 = (double) Math.round(tax2 * 100) / 100;
//creates variable for amount paid
double paid1 = 0;
//prints info to the user and asks how much cash they received
System.out.println("You entered $" + total1 + "\n" + "Total with tax = $" + tax1 + "\n" + "Please enter how much cash was paid by the customer. The amount of change owed to the customer will be displayed.");
paid1 = myInput.nextDouble();
//checks if customer has paid enough
if (tax1 > paid1) {
double owed1 = (tax1-paid1);
System.out.println("The customer still owes $" + owed1 + "!");
} else if (tax1 == paid1) { //checks if the customer has given exact change
System.out.println("The customer has paid the exact amount. You don't have to give them any change.");
} else if (tax1 < paid1) {
//starts change calculations
//variables for money units
double oneHundred = 100;
double fifty = 50;
double twenty = 20;
double ten = 10;
double five = 5;
double toonie = 2;
double loonie = 1;
double quarter = 0.25;
double dime = 0.10;
double nickel = 0.05;
double penny = 0.01;
//variable for change owed (rounded to 2 decimal places
double change1 = Math.round((paid1-tax1)*100)/100;
//calculates remainder
double oneHundredMod = (change1 % oneHundred);
//divides and removes decimal places
double oneHundredOwed = (change1 / oneHundred);
String oneHundredOwed1 = String.valueOf((int) oneHundredOwed);
//does the same thing for fifty
double fiftyMod = (oneHundredMod % fifty);
double fiftyOwed = (oneHundredMod / fifty);
String fiftyOwed1 = String.valueOf((int) fiftyOwed);
//twenties
double twentyMod = (fiftyMod % twenty);
double twentyOwed = (fiftyMod / twenty);
String twentyOwed1 = String.valueOf((int) twentyOwed);
//tens
double tenMod = (twentyMod % ten);
double tenOwed = (twentyMod / ten);
String tenOwed1 = String.valueOf((int) tenOwed);
//fives
double fiveMod = (tenMod % five);
double fiveOwed = (tenMod / five);
String fiveOwed1 = String.valueOf((int) fiveOwed);
//toonies
double tooniesMod = (fiveMod % toonie);
double tooniesOwed = (fiveMod / toonie);
String tooniesOwed1 = String.valueOf((int) tooniesOwed);
//loonies
double looniesMod = (tooniesMod % loonie);
double looniesOwed = (tooniesMod / loonie);
String looniesOwed1 = String.valueOf((int) looniesOwed);
//quarters
double quartersMod = (looniesMod % quarter);
double quartersOwed = (looniesMod / quarter);
String quartersOwed1 = String.valueOf((int) quartersOwed);
//dimes
double dimesMod = (quartersMod % dime);
double dimesOwed = (quartersMod / dime);
String dimesOwed1 = String.valueOf((int) dimesOwed);
//nickels
double nickelsMod = (dimesMod % nickel);
double nickelsOwed = (dimesMod / nickel);
String nickelsOwed1 = String.valueOf((int) nickelsOwed);
//and finally, pennies!
double penniesMod = (nickelsMod % penny);
double penniesOwed = (nickelsMod / penny);
String penniesOwed1 = String.valueOf((int) penniesOwed);
System.out.println("TOTAL CHANGE:" + "\n" + "\n" + "$100 Bill(s) = " + oneHundredOwed1 + "\n" + "$50 Bill(s) = " + fiftyOwed1 + "\n" + "$20 Bill(s) = " + twentyOwed1 + "\n" + "$10 Bill(s) = " + tenOwed1 + "\n" + "$5 Bill(s) = " + fiveOwed1 + "\n" + "Toonie(s) = " + tooniesOwed1 + "\n" +"Loonie(s) = " + looniesOwed1 + "\n" + "Quarter(s) = " + quartersOwed1 + "\n" + "Dime(s) = " + dimesOwed1 + "\n" + "Nickel(s) = " + nickelsOwed1 + "\n" + "Pennies = " + penniesOwed1);
}
}//end main
}// end Decisions1

How would I make it so the output will round up to two decimal places?

My code here is working fine but whenever I run it, it doesn't seem to round up and I don't know what to add and where to add it.
package com.mycompany.billofsale;
public class Billofsale {
public static void main(String[] args) {
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
System.out.println("The total is "+s
+ "\n The tax is "+result
+ "\n The total cost with tax is "+result2
+ "\n The change is "+result3);
}
}
You need to use DecimalFormat to format all the numbers that you want to print to the decimals that you want.
Try with this code:
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
DecimalFormat format = new DecimalFormat(".00");
format.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
+ "\n The change is " + format.format(result3));

Display all iterations of for loop

I created a method that calculates and displays values of simple interest based on the amount of years. I want to show all years so for example if the years is 5, I want to show the value for years 1, 2, 3, 4, 5
This is my code so far
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
My output is
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
5.0-->$6250.0
But I want it to also display the previous years like
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
What do I need to do to display the previous years?
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
in the code above you are reassigning interest if method is equal to "simple". so, the last assigned value is returned.
use += to concatenate new results to interest or just return String[] containing each result as an individual element and then iterate over it.
public static String numbers(String method, double principal, double rate, double years)
{
String interest = "";
for (double digit = 1; digit <= years; digit++)
{
if (method.equals(Simple))
{
double simpleInterest = principal + (principal * (rate / 100) * digit);
interest += "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
You have to calculate simpleInterest for every year simpleInterest = principal + (principal * (rate / 100) * digit); here digit represent year.
and also use += operator to concatenate results to interest and return it.
You can also use string concat() method
Here is the syntax of this method: public String concat(String s).
you can use it like this: interest = interest.concat(digit + "-->$" + simpleInterest + "\n");
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
System.out.println("Principal: $" + principal + ',' + " Rate: " + rate + "\n"+ "Year Simple Interest Amount\n");
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
simpleInterest = principal + (principal * (rate / 100) * digit);
interest += digit + "-->$" + simpleInterest + "\n";
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
Output:
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0

Repeated Output, have to end the program manually

I am a beginner and not tried the following program which is giving me repeated output.. I have to end the program manually in eclipse. Not able to figure out the problem. Please advice. Any other tips are welcome.
import java.util.Scanner;
public class Sales_Amount {
public static void main(String[] args) {
final double Base_Salary = 25000;
double Commission = 0;
double Total_Salary;
double X;
double Y;
Scanner input = new Scanner(System. in );
System.out.print("Enter Sales Amount: ");
double Sales = input.nextDouble();
while (Commission < 25001) {
if (Sales <= 5000); {
Total_Salary = Base_Salary + (0.08 * Sales);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 5000 && Sales < 10001); {
X = Sales - 5000;
Total_Salary = Base_Salary + (0.08 * 5000) + (0.10 * X);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 10001); {
Y = Sales - 10000;
Total_Salary = Base_Salary + (.08 * 5000) + (.10 * 10000) + (.12 * Y);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
}
}
}
Add commission++ before the end of the loop.

NullPointerException at actionPerformed. Not sure why

I am creating a Java program that uses a GUI to display a mortgage payment. I am trying to output to a textArea the payments that will be made for the mortgage. Here is my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class MortgageGui extends JFrame implements ActionListener {
// Set two-places for decimal format
DecimalFormat twoPlaces = new DecimalFormat("$0.00");
// Declare variable for calculation
Double loanAmt;
double interestRate;
double monthlyPayment;
int payment;
String amount;
JTextField loanAmount;
JComboBox loanTypeBox;
JLabel paymentOutput;
JTextArea paymentList;
// Build arrays for mortgages
double[] mortgage1 = {7.0, 5.35, 0.0}; // (years, interest, monthly payment)
double[] mortgage2 = {15.0, 5.5, 0.0}; // (years, interest, monthly payment)
double[] mortgage3 = {30.0, 5.75, 0.0}; // (years, interest, monthly payment)
public MortgageGui() {
super("Mortgage Calculator");
setLookAndFeel();
setSize(350, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Loan Amount Panel
JPanel loanAmtPanel = new JPanel();
JLabel loanAmtLabel = new JLabel("Loan Amount: ", JLabel.LEFT);
JTextField loanAmount = new JTextField(10);
loanAmtPanel.add(loanAmtLabel);
loanAmtPanel.add(loanAmount);
// Loan Type Panel
JPanel loanTypePanel = new JPanel();
JLabel loanTypeLabel = new JLabel("Loan Type: ", JLabel.LEFT);
String[] items = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
JComboBox loanTypeBox = new JComboBox(items);
loanTypePanel.add(loanTypeLabel);
loanTypePanel.add(loanTypeBox);
// Calculate Button Panel
JPanel calculatePanel = new JPanel();
JButton calcButton = new JButton("Calculate Paytment");
calcButton.addActionListener(this);
calculatePanel.add(calcButton);
// Monthly Payment Panel
JPanel paymentPanel = new JPanel();
JLabel paymentLabel = new JLabel("Monthly Payment: ", JLabel.LEFT);
JLabel paymentOutput = new JLabel("Calculated Payment");
paymentPanel.add(paymentLabel);
paymentPanel.add(paymentOutput);
// View Payments Panel
JPanel viewPayments = new JPanel();
JTextArea paymentList = new JTextArea("", 17, 27);
paymentList.setEditable(false);
paymentList.setLineWrap(true);
viewPayments.add(paymentList);
// Add panels to win Panel
JPanel win = new JPanel();
BoxLayout box = new BoxLayout(win, BoxLayout.Y_AXIS);
win.setLayout(box);
win.add(loanAmtPanel);
win.add(loanTypePanel);
win.add(calculatePanel);
win.add(paymentPanel);
win.add(viewPayments);
add(win);
// Make window visible
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore
}
}
public void actionPerformed(ActionEvent e) {
// Clear payment list
paymentList.setText("");
// Get loan amount from textfield
String amount = loanAmount.getText();
loanAmt = Double.valueOf(amount).doubleValue();
// Find which mortgate array to use from combobox
Object obj = loanTypeBox.getSelectedItem();
String loanSelected = obj.toString();
// Run the calculation based on the mortgage arrays
// 7-year loan
if (loanSelected.equals("7 years at 5.35%")) {
// Calculate payment, interest, and remaining
mortgage1[2] = (loanAmt + (loanAmt * (mortgage1[1] / 100))) / (mortgage1[0] * 12);
double interest1 = (loanAmt * (mortgage1[1] / 100)) / 84;
double amountRemaining1 = loanAmt + (loanAmt * (mortgage1[1] / 100));
// Loop through payments
for (int payment = 1; payment <=84; payment++) {
// Deduct one payment from the balance
amountRemaining1 = amountRemaining1 - mortgage1[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage1[2]) +
" / " + "Interest: $" + twoPlaces.format(interest1) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining1) + "\n");
}
} else {
// 15-year loan
if (loanSelected.equals("15 years at 5.5%")) {
// Calculate payment, interest, and remaining
mortgage2[2] = (loanAmt + (loanAmt * (mortgage2[1] / 100))) / (mortgage2[0] * 12);
double interest2 = (loanAmt * (mortgage2[1] / 100)) / 180;
double amountRemaining2 = loanAmt + (loanAmt * (mortgage2[1] / 100));
// Loop through payments
for (int payment = 1; payment <=180; payment++) {
// Deduct one payment from the balance
amountRemaining2 = amountRemaining2 - mortgage2[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage2[2]) +
" / " + "Interest: $" + twoPlaces.format(interest2) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining2) + "\n");
}
} else {
//30-year loan
//Calculate payment, interest, and remaining
mortgage3[2] = (loanAmt + (loanAmt * (mortgage3[1] / 100))) / (mortgage3[0] * 12);
double interest3 = (loanAmt * (mortgage3[1] / 100)) / 360;
double amountRemaining3 = loanAmt + (loanAmt * (mortgage3[1] / 100));
// Loop through payments
for (int payment = 1; payment <=360; payment++) {
// Deduct one payment from the balance
amountRemaining3 = amountRemaining3 - mortgage3[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage3[2]) +
" / " + "Interest: $" + twoPlaces.format(interest3) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining3) + "\n");
}
}
}
}
public static void main(String[] arguments) {
MortgageGui calc = new MortgageGui();
}
}
When I run the program I see the GUI but when I hit the button to calculate I get this in the console:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at MortgageGui.actionPerformed(MortgageGui.java:100)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I cannot figure out where I am going wrong. Please help!
You're redeclaring the paymentList variable in the class's constructor
JTextArea paymentList = new JTextArea("", 17, 27);
The variable inside of the constructor "shadows" the class field, so that the constructor doesn't see the class field. This local variable is visible only within the constructor (since it was declared inside of it) and the class field will remain null.
Solution: don't re-declare the variable in the constructor. It's OK to initialize it there, but don't re-declare it:
paymentList = new JTextArea("", 17, 27);
On a more general note, you should always inspect the variables on the line that throws the NPE because one of them is null. If you saw that it was paymentList, you'd quickly be able to identify what I just showed you and you wouldn't need our help, which is kind of the goal of this forum -- to get you to be able to solve things on your own.
Edit:
Also please note that you do this error more than once in your code. I'll let you find the other occurrences of this.
Edit 2:
Consider putting your JTextArea in a JScrollPane. Consider using some decent layout managers and not setting the size of the GUI but rather letting the layout managers do this for you.
The field:
JTextArea paymentList;
is never initialized, so it is null when you try to set the value to "".
The same goes for loanAmount.
#Hovercraft Full Of Eels has explained why they aren't initialised as you think they are, in another answer...
Bonus tip: the line
loanAmt = Double.valueOf(amount).doubleValue();
will throw an exception if the loan amount is blank (or not a valid double) - you'll need to use a try-catch to handle this
"loanAmount", "loanTypeBox", "paymentList"
For these three, You have to comment out these three lines, because you have already declared these, only assignment needed;
//JTextField loanAmount = new JTextField(10); // loanAmount: Already declared, only assignment needed
loanAmount = new JTextField(10);
//JComboBox loanTypeBox = new JComboBox(items); // loanTypeBox: Already declared, only assignment needed
loanTypeBox = new JComboBox(items);
//JTextArea paymentList = new JTextArea("", 17, 27);// paymentList: Already declared, only assignment needed
paymentList = new JTextArea("", 17, 27);
Here is the updated code;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class MortgageGui extends JFrame implements ActionListener {
// Set two-places for decimal format
DecimalFormat twoPlaces = new DecimalFormat("$0.00");
// Declare variable for calculation
Double loanAmt;
double interestRate;
double monthlyPayment;
int payment;
String amount;
JTextField loanAmount;
JComboBox loanTypeBox;
JLabel paymentOutput;
JTextArea paymentList;
// Build arrays for mortgages
double[] mortgage1 = { 7.0, 5.35, 0.0 }; // (years, interest, monthly
// payment)
double[] mortgage2 = { 15.0, 5.5, 0.0 }; // (years, interest, monthly
// payment)
double[] mortgage3 = { 30.0, 5.75, 0.0 }; // (years, interest, monthly
// payment)
public MortgageGui() {
super("Mortgage Calculator");
setLookAndFeel();
setSize(350, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Loan Amount Panel
JPanel loanAmtPanel = new JPanel();
JLabel loanAmtLabel = new JLabel("Loan Amount: ", JLabel.LEFT);
// JTextField loanAmount = new JTextField(10); // loanAmount: Already declared, only assignment needed
loanAmount = new JTextField(10);
loanAmtPanel.add(loanAmtLabel);
loanAmtPanel.add(loanAmount);
// Loan Type Panel
JPanel loanTypePanel = new JPanel();
JLabel loanTypeLabel = new JLabel("Loan Type: ", JLabel.LEFT);
String[] items = { "7 years at 5.35%", "15 years at 5.5%",
"30 years at 5.75%" };
// JComboBox loanTypeBox = new JComboBox(items); // loanTypeBox: Already declared, only assignment needed
loanTypeBox = new JComboBox(items);
loanTypePanel.add(loanTypeLabel);
loanTypePanel.add(loanTypeBox);
// Calculate Button Panel
JPanel calculatePanel = new JPanel();
JButton calcButton = new JButton("Calculate Paytment");
calcButton.addActionListener(this);
calculatePanel.add(calcButton);
// Monthly Payment Panel
JPanel paymentPanel = new JPanel();
JLabel paymentLabel = new JLabel("Monthly Payment: ", JLabel.LEFT);
JLabel paymentOutput = new JLabel("Calculated Payment");
paymentPanel.add(paymentLabel);
paymentPanel.add(paymentOutput);
// View Payments Panel
JPanel viewPayments = new JPanel();
// JTextArea paymentList = new JTextArea("", 17, 27); // paymentList: Already declared, only assignment needed
paymentList = new JTextArea("", 17, 27);
paymentList.setEditable(false);
paymentList.setLineWrap(true);
viewPayments.add(paymentList);
// Add panels to win Panel
JPanel win = new JPanel();
BoxLayout box = new BoxLayout(win, BoxLayout.Y_AXIS);
win.setLayout(box);
win.add(loanAmtPanel);
win.add(loanTypePanel);
win.add(calculatePanel);
win.add(paymentPanel);
win.add(viewPayments);
add(win);
// Make window visible
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore
}
}
public void actionPerformed(ActionEvent e) {
// Clear payment list
paymentList.setText("");
// Get loan amount from textfield
String amount = loanAmount.getText();
loanAmt = Double.valueOf(amount).doubleValue();
// Find which mortgate array to use from combobox
Object obj = loanTypeBox.getSelectedItem();
String loanSelected = obj.toString();
// Run the calculation based on the mortgage arrays
// 7-year loan
if (loanSelected.equals("7 years at 5.35%")) {
// Calculate payment, interest, and remaining
mortgage1[2] = (loanAmt + (loanAmt * (mortgage1[1] / 100)))
/ (mortgage1[0] * 12);
double interest1 = (loanAmt * (mortgage1[1] / 100)) / 84;
double amountRemaining1 = loanAmt
+ (loanAmt * (mortgage1[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 84; payment++) {
// Deduct one payment from the balance
amountRemaining1 = amountRemaining1 - mortgage1[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage1[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest1) + " / "
+ "Remaining: $" + twoPlaces.format(amountRemaining1)
+ "\n");
}
} else {
// 15-year loan
if (loanSelected.equals("15 years at 5.5%")) {
// Calculate payment, interest, and remaining
mortgage2[2] = (loanAmt + (loanAmt * (mortgage2[1] / 100)))
/ (mortgage2[0] * 12);
double interest2 = (loanAmt * (mortgage2[1] / 100)) / 180;
double amountRemaining2 = loanAmt
+ (loanAmt * (mortgage2[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 180; payment++) {
// Deduct one payment from the balance
amountRemaining2 = amountRemaining2 - mortgage2[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage2[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest2)
+ " / " + "Remaining: $"
+ twoPlaces.format(amountRemaining2) + "\n");
}
} else {
// 30-year loan
// Calculate payment, interest, and remaining
mortgage3[2] = (loanAmt + (loanAmt * (mortgage3[1] / 100)))
/ (mortgage3[0] * 12);
double interest3 = (loanAmt * (mortgage3[1] / 100)) / 360;
double amountRemaining3 = loanAmt
+ (loanAmt * (mortgage3[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 360; payment++) {
// Deduct one payment from the balance
amountRemaining3 = amountRemaining3 - mortgage3[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage3[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest3)
+ " / " + "Remaining: $"
+ twoPlaces.format(amountRemaining3) + "\n");
}
}
}
}
public static void main(String[] arguments) {
MortgageGui calc = new MortgageGui();
}
}
And the output is as below with no any errors observed on the console;

Categories

Resources