Java radio buttons - java

I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
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.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}

You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.

Related

Random Number won't appear in a JTextField

I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.

Unable to getText the value of string

I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String

I've been having problems running this program it compiles but doesn't run properly. When I run it and attempt to perform the calculations it spits out a bunch errors. I think it has to with variable types. Here is the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class area extends JFrame implements ActionListener, ItemListener{
//row 1
JPanel row1 = new JPanel();
JLabel select = new JLabel("Please select what you would like to caculate the area and volume of.");
//row 2
JPanel row2 = new JPanel();
JCheckBox circle = new JCheckBox("Circle", false);
JCheckBox cube = new JCheckBox("Cube", false);
//row 3
JPanel row3 = new JPanel();
JLabel radlab = new JLabel("Radius of the circle (in cm)");
JTextField rad = new JTextField(3);
JLabel sidelab = new JLabel("A side of the cube (in cm)");
JTextField side = new JTextField(3);
//row4
JPanel row4 = new JPanel();
JButton solve = new JButton("Solve!");
//row 5
JPanel row5 = new JPanel();
JLabel areacallab = new JLabel("Area");
JTextField areacal = new JTextField(10);
JLabel volumelab = new JLabel("Volume");
JTextField volume = new JTextField(10);
public area(){
setTitle("Area Caculator");
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//disables all text areas
rad.setEnabled(false);
side.setEnabled(false);
areacal.setEnabled(false);
volume.setEnabled(false);
//add listeners
circle.addItemListener(this);
cube.addItemListener(this);
solve.addActionListener(this);
FlowLayout one = new FlowLayout(FlowLayout.CENTER);
setLayout(one);
row1.add(select);
add(row1);
row2.add(circle);
row2.add(cube);
add(row2);
row3.add(radlab);
row3.add(rad);
row3.add(sidelab);
row3.add(side);
add(row3);
row4.add(solve);
add(row4);
row5.add(areacallab);
row5.add(areacal);
row5.add(volumelab);
row5.add(volume);
add(row5);
}
public void circlepick(){
//cube.setCurrent(false);
cube.setEnabled(false);
rad.setEnabled(true);
}
public void cubepick(){
circle.setEnabled(false);
side.setEnabled(true);
}
#Override
public void itemStateChanged(ItemEvent event) {
Object item = event.getItem();
if (item == circle){
circlepick();
}
else if (item == cube){
cubepick();
}
}
#Override
public void actionPerformed(ActionEvent evt){
//String radi = rad.getText();
//String sid = side.getText();
//circlesolve();
//cubesolve();
String radi = rad.getText();
String sid = side.getText();
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
double cirarea = Math.PI * Math.pow(radius, 2);
double cirvolume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
double cubearea = Math.pow(length, 2);
double cubevolume = Math.pow(length, 3);
areacal.setText("" + cirarea + cubearea + "");
volume.setText("" + cirvolume + cubevolume + "");
}
public static void main(String[] args) {
area are = new area();
}
}
Here are the errors is printing out when attempting to perform the math (sorry it really long).
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1038)
at java.lang.Double.parseDouble(Double.java:548)
at area.actionPerformed(area.java:112)
...
Thanks so much in advance for an help!
When calling the functions:
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
either radi or sid is am Empty String, thats what
java.lang.NumberFormatException: empty String
tells you.
You might consider adding a System.out.println(raid + ", " + sid) before parsing to check what values are empty Strings and make sure, that the Strings are not empty.
Double.parseDouble(String s) throws a NumberFormatException when the given String s can not be parsed into a double value.

Components added outside constructor wont appear

I have one tab that needs to update using one of two methods in it's class while the program is running, for that reason I'm adding components inside the methods, and I cannot get any of them to display. As far as I can tell it's because they are outside the constructor, I used to declare them all inside the methods but moved it to try and fix the problem. Any help would be greatly appreciated.
I apologise it's a bit messy, I've been trying to fix the problem, a bit blindly.
Also the code compiles fine, and println outputs in code display as expected.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assgui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
/**
*
* #author Hugh
*/
public class ResultPanel extends JPanel {
static String[][] activityString = new String[31][2];
static String[][] foodString = new String[36][2];
String weighstr, foodstr, servstr, kjstr, actstr, hourstr, minstr, metstr;
JLabel uw = new JLabel ("User Weight: ");
JLabel weigh = new JLabel (weighstr);
JLabel kg = new JLabel(" kg");
JLabel sel1 = new JLabel("Food: ");
JLabel sel2 = new JLabel(foodstr);
JLabel sel3 = new JLabel(" - kj ");
JLabel sel4 = new JLabel(kjstr);
JLabel sel5 = new JLabel(" , Servings: ");
JLabel sel6 = new JLabel(servstr);
JLabel sel7 = new JLabel("Activity for comparison: ");
JLabel sel8 = new JLabel(actstr);
JLabel sel9 = new JLabel(" Time required to balance: ");
JLabel sel10 = new JLabel(hourstr);
JLabel sel11 = new JLabel(" hours");
JLabel sel12 = new JLabel(minstr);
JLabel sel13 = new JLabel(" minutes");
JLabel smlspace = new JLabel(" ");
JLabel medspace = new JLabel(" ");
JLabel lrgspace = new JLabel(" ");
JLabel auw = new JLabel("User Weight: ");
JLabel aweigh = new JLabel(weighstr);
JLabel akg = new JLabel(" kg");
JLabel asel1 = new JLabel("Activity: ");
JLabel asel2 = new JLabel(actstr);
JLabel asel3 = new JLabel(" - MET ");
JLabel asel4 = new JLabel(metstr);
JLabel asel5 = new JLabel(" , Duration: ");
JLabel asel6 = new JLabel(hourstr);
JLabel asel7 = new JLabel(" hour ");
JLabel asel8 = new JLabel(minstr);
JLabel asel9 = new JLabel(" minutes ");
JLabel asel10 = new JLabel("Food for comparison: ");
JLabel asel11 = new JLabel(foodstr);
JLabel asel12 = new JLabel(" Servings to balance: ");
JLabel asel13 = new JLabel(servstr);
JLabel asmlspace = new JLabel(" ");
JLabel amedspace = new JLabel(" ");
JLabel alrgspace = new JLabel(" ");
Public ResultPanel() {
setBackground(Color.GREEN);
setPreferredSize(new Dimension(650, 600));
{
public void activityPaint (String[][] actstring, String[][] foodstring, double weight, int activity, int hour, int min, int food, double servings) {
System.out.println("act1");
weighstr = Double.toString(weight);
actstr = activityString[activity][0];
hourstr = Integer.toString(hour);
minstr = Integer.toString(min);
metstr = activityString[activity][1];
foodstr = foodString[food][0];
servstr = Double.toString(servings);
add(lrgspace);
add(uw);
add(weigh);
add(kg);
add(medspace);
add(sel1);
add(sel2);
add(sel3);
add(sel4);
add(sel5);
add(sel6);
add(sel7);
add(sel8);
add(sel9);
add(sel10);
add(sel11);
add(sel12);
add(sel13);
}
public void foodPaint(String[][] foodstring, String[][] actstring, double weight, int food, int servings, int activity, int hour, int min) {
System.out.println("food1");
weighstr = Double.toString(weight);
foodstr = foodString[food][0];
servstr = Integer.toString(servings);
kjstr = foodString[food][1];
actstr = activityString[activity][0];
hourstr = Integer.toString(hour);
minstr = Integer.toString(min);
add(lrgspace);
add(uw);
add(weigh);
add(kg);
add(medspace);
add(sel1);
add(sel2);
add(sel3);
add(sel4);
add(sel5);
add(sel6);
add(sel7);
add(sel8);
add(sel9);
add(sel10);
add(sel11);
add(sel12);
add(sel13);
}
}
Does your main method (or whatever method) that creates this JPanel also call the activityPaint(...) and foodPaint(...) methods? If those methods are not called then they will never be added to the panel it seems. If you want everything to be added when you create the JPanel then you must have your constructor call activityPaint() and foodPaint().
If the values of your JLables can't be set until something else occurs (like user input), then you can add the components when the JPanel is created and then later call the setText(...) method. Just be sure if you do that to also set the size since changing the text will effect that. I prefer to use nameofjpanel.setSize(nameofjpanel.getPreferredSize()).
Hope this helps you and I didn't completely miss what you're going for here.

Java Mortgage Calculator Reading a Sequential File [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I populate jcombobox from a textfile?
OK, I have an issue here that I cannot quiet figure out. I have a file that has variables on each line of: 5.35, 5.5, 5.75 in a file called apr.txt. I am reading the file and need to populate the file into a JComboBox. So far I have the file being read fine but cannot figure how to populate it into the JComboBox. This must be something easy. Can someone help point me in the proper direction?
Thank you for your help in advance.
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.JComboBox;
public class MortgageCalculatorGUI9 extends JFrame implements ActionListener
{
// Declarations
//double [] Interest = {5.35, 5.5, 5.75};
int [] Length = {7, 15, 30};
double [] file_data = new double[3];
JLabel mortgagelabel = new JLabel( "Principal Amount:$ " );
JLabel paymentLabel = new JLabel( "Monthly Payment: " );
JLabel intRateLabel = new JLabel( "Interest Rate %: " );
JLabel termLabel = new JLabel( "Length of Loan of Loan in Years: " );
JTextField mortgagePrincipal = new JTextField(7);
JTextField Payment = new JTextField(7);
//JTextField intRateText = new JTextField(3);
JComboBox intRateBox = new JComboBox();
JTextField termText = new JTextField(3);
JButton b7_535 = new JButton( "7 years at 5.35%" );
JButton b15_55 = new JButton( "15 years at 5.50%" );
JButton b30_575 = new JButton( "30 years at 5.75%");
JButton exitButton = new JButton( "Exit" );
JButton clearButton = new JButton( "Clear All" );
JButton calculateButton = new JButton( "Calculate Loan" );
JTextArea LoanPayments = new JTextArea(20,50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public MortgageCalculatorGUI9()
{
//GUI setup
super("Mortgage Calculator 1.0.5");
setSize(800, 400);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(3,1)); Container grid = getContentPane();
grid.setLayout(new GridLayout(4,0,4,4)); pane.add(grid);
pane.add(scroll);
grid.add(mortgagelabel);
grid.add(mortgagePrincipal);
grid.add(intRateLabel);
//grid.add(intRateText);
grid.add (intRateBox);
grid.add(termLabel);
grid.add(termText);
grid.add(paymentLabel);
grid.add(Payment);
grid.add(b7_535);
grid.add(b15_55);
grid.add(b30_575);
grid.add(calculateButton);
grid.add(clearButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
//add GUI functionality
calculateButton.addActionListener (this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
b7_535.addActionListener(this);
b15_55.addActionListener(this);
b30_575.addActionListener(this);
mortgagePrincipal.addActionListener(this);
//intRateText.addActionListener(this);
intRateBox.addActionListener (this);
termText.addActionListener(this);
Payment.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object command = e.getSource();
if (command == exitButton)
{
System.exit(0);
}
else if (command == b7_535)
{
calcLoan(Length[0], file_data[0]);
}
else if (command == b15_55)
{
calcLoan(Length[1], file_data[1]);
}
else if (command == b30_575)
{
calcLoan(Length[2], file_data[2]);
}
else if (command == calculateButton )
{
double terms = 0;
double rates = 0;
try
{
terms = Double.parseDouble(termText.getText());
//rates = Double.parseDouble(intRateText.getText());
read_File ();
}
catch (Exception ex)
{
LoanPayments.setText("Invalid term or rate Amount");
return;
}
calcLoan(terms, rates);
}
else if (command == clearButton)
{
mortgagePrincipal.setText("");
Payment.setText("");
//intRateText.setText("");
termText.setText("");
LoanPayments.setText("");
}
}
//Input File
public void read_File()
{
File inFile = new File("apr.txt");
try
{
BufferedReader istream = new BufferedReader(new FileReader(inFile));
for(int x=0;x<6;x++)
{
file_data[x]=Double.parseDouble (istream.readLine());
}
}
catch (Exception ex)
{
LoanPayments.setText ("Could Not Read From File.");
return;
}
}
//this is what needs to be done
private void calcLoan(double terms, double rates)
{
termText.setText(String.valueOf(terms) );
//intRateText.setText(String.valueOf(rates));
double amount = 0;
try
{
amount = Double.parseDouble(mortgagePrincipal.getText());
}
catch (Exception ex)
{
LoanPayments.setText("Invalid mortgage Amount");
return;
}
double interestRate = rates;
// Calculations
double intRate = (interestRate / 100) / 12;
int Months = (int)terms * 12;
double rate = (intRate / 12);
double payment = amount * intRate / (1 - (Math.pow(1/(1 + intRate), Months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
double[] balanceArray = new double[Months];
double[] interestArray = new double[Months];
double[] monthArray = new double[Months];
NumberFormat Money = NumberFormat.getCurrencyInstance();
Payment.setText(Money.format(payment));
LoanPayments.setText("Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while(currentMonth < Months)
{
//create loop calculations
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t" + Money.format(MonthlyAmt) + "\t" + Money.format(MonthlyInterest) + "\t" + Money.format(remainingPrincipal) + "\n");
balanceArray[currentMonth] = MonthlyAmt;
interestArray[currentMonth] = MonthlyInterest;
monthArray[currentMonth] = currentMonth;
}
}
public static void main(String[] args)
{
MortgageCalculatorGUI9 frame= new MortgageCalculatorGUI9();
}
}
Have you looked at the JComboBox API for a suitable method? If you start there, you'll likely get the right answer faster than asking in StackOverflow (hint it starts with "add... and ends with ...Item") ;)

Categories