Charts and Reading Files
Sorry if this duplicates...It errored the first time I tried to post
I'm a newbie in a java class and need help. I need help with 2 things.
The first item is I need to display a pie chart on my gui that displays the principal amount and the total interest paid. I have a start for a pie chart, but am struggling with getting the calculations for the total interest paid and how to display the chart on my panel.
The second item is I need to read a text file that literally only displays "7 15 30" in the contents and have it assign those values to the term combo box. I started some code, but am stuck on how to proceed. Currently, my term combo box has the selections already defined, but that was how it was supposed to be last week not this week.
Any help I can get through Saturday would be great (my assignment is due by midnight on 05/19), but even if it is later than that, I would like to know. I want to eventually be a programmer, so even knowledge late is better than no knowledge at all.
Thank you for any help! (I hope I attached my code correctly.)
Christy
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.io.*;
import java.util.*;
publicclass MortgageCalculationsWeek5extends JFrame
{
//Initialize variables
JButton calculateButton, clearButton, exitButton, pieButton;
JTextField principalField, interestField, termField, monthlyField, termResult, interestResult;
JTextArea displayArea;
JScrollPane displayPane;
JLabel principalLabel, termLabel, interestLabel, interestRateLabel, TermLabel, monthlyLabel;
JLabelintructionLabel1, intructionLabel2, intructionLabel3, intructionLabel4, intructionLabel5, intructionLabel6;
JPanel mainPanel, buttonPanel;
JComboBox termCombo, interestCombo;
String principalString, interestString, termString, interestBox, termYears;
double principalAmt, loanInterest, loanTerm, monthlyPayment, interestPayment, principalPayment, remainingBalance, months, monthlyInt;
publicstaticvoid main (String[] args)
{
new MortgageCalculationsWeek5();
}
public MortgageCalculationsWeek5()
{
this.setSize(900,800);
this.setLocation(100,0);
this.setTitle("MORTGAGE CALCULATOR");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainPanel =new JPanel();
buttonPanel =new JPanel();
intructionLabel1 =new JLabel("Instructions:Enter in the principal amount that you want. Next either enter in the interest and term or select from the drop-down lists. After entering");
mainPanel.add(intructionLabel1);
intructionLabel2 =new JLabel("the data, click on the CALCULATE button to calculate. If you want to enter in different information, click on the CLEAR button to clear the fields and start");
mainPanel.add(intructionLabel2);
intructionLabel3 =new JLabel("over. When you are done, click on the EXIT button. ");
mainPanel.add(intructionLabel3);
intructionLabel4 =new JLabel("");
mainPanel.add(intructionLabel4);
intructionLabel5 =new JLabel("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
mainPanel.add(intructionLabel5);
//principal label and text field
principalLabel =new JLabel("Principal:");
mainPanel.add(principalLabel);
principalField =new JTextField(10);
mainPanel.add(principalField);
//interest label and text field
interestLabel =new JLabel("Interest Rate (APR):");
mainPanel.add(interestLabel);
interestField =new JTextField(4);
mainPanel.add(interestField);
//interest rate combo box
String[] InterestRates ={"5.35","5.50","5.75"};
interestCombo =new JComboBox(InterestRates);
interestCombo.addItemListener(new InterestComboListener());
interestCombo.setEditable(false);
mainPanel.add(interestCombo);
//term label and text field
termLabel =new JLabel("Term (in years):");
mainPanel.add(termLabel);
termField =new JTextField(5);
mainPanel.add(termField);
//term combo box
String[] TermYears ={"7","15","30"};
termCombo =new JComboBox(TermYears);
termCombo.setSelectedIndex(0);
termCombo.addItemListener(new TermComboListener());
termCombo.setEditable(false);
mainPanel.add(termCombo);
//term label and text field
monthlyLabel =new JLabel("Monthly Payment:");
mainPanel.add(monthlyLabel);
monthlyField =new JTextField(7);
mainPanel.add(monthlyField);
//display area
displayArea =new JTextArea(10,70);
displayArea.setEditable(false);
displayPane =new JScrollPane(displayArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mainPanel.add(displayPane);
//buttons
calculateButton =new JButton("Calculate");
calculateButton.addActionListener(new CalculateButtonListener());
buttonPanel.add(calculateButton);
clearButton =new JButton("Clear Selections");
clearButton.addActionListener(new ClearFieldsAction());
buttonPanel.add(clearButton);
exitButton =new JButton("Exit Program");
exitButton.addActionListener(new ExitProgramAction());
buttonPanel.add(exitButton);
this.setLayout(new BorderLayout());
this.add(mainPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
this.setVisible(true);
}
privatevoid SetTextFunction(String text)
{
monthlyField.setText(text);
interestField.setText(interestBox);
}
class TermComboListenerimplements ItemListener
{
//Listen to the combo box
publicvoid itemStateChanged(ItemEvent ie)
{
JComboBox cb1 = (JComboBox)ie.getSource();// the source of the event is the combo box
String termYear = (String)cb1.getSelectedItem();
termField.setText(termYear);
}
}
class InterestComboListenerimplements ItemListener
{
//Listen to the combo box
publicvoid itemStateChanged(ItemEvent ie)
{
JComboBox cb1 = (JComboBox)ie.getSource();// the source of the event is the combo box
String interestBox = (String)cb1.getSelectedItem();
interestField.setText(interestBox);
}
}
class CalculateButtonListenerimplements ActionListener
{
publicvoid actionPerformed (ActionEvent e)
{
principalString = principalField.getText();
interestString = interestField.getText();
termString = termField.getText();
//get user input and display exceptions
try
{
principalAmt = Double.parseDouble(principalString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null,"Error with the principal entered. Field is either blank or invalid data entered.","Exception #1", JOptionPane.ERROR_MESSAGE);
principalField.requestFocus();
return;
}
try
{
loanInterest = Double.parseDouble(interestString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null,"Error with the interest entered. Field is either blank or invalid data entered.","Exception #2", JOptionPane.ERROR_MESSAGE);
interestField.requestFocus();
return;
}
try
{
loanTerm = Double.parseDouble(termString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null,"Error with the term entered. Field is either blank or invalid data entered.","Exception #3", JOptionPane.ERROR_MESSAGE);
termField.requestFocus();
return;
}
// Display principal, interest, and loan balance of entire term
months = loanTerm * 12;
monthlyInt = (loanInterest / 100) / 12;
monthlyPayment = (principalAmt * monthlyInt) / (1 - Math.pow(1 / (1 + monthlyInt), months));
NumberFormat Currency = NumberFormat.getCurrencyInstance();
SetTextFunction("" + Currency.format(monthlyPayment));
for (int i = 1; i <= months; ++i)
{
interestPayment = principalAmt * monthlyInt;
principalPayment = monthlyPayment - interestPayment;
remainingBalance = principalAmt - principalPayment;
displayArea.append("\n#" + i +"\t\t\tP=" + Currency.format(principalPayment) +"\t\t\tI=" + Currency.format(interestPayment)
+"\t\t\tB=" + Currency.format(remainingBalance) +"\n");
principalAmt -= principalPayment;// calculate until payments are done
}
}
}//END ACTIONLISTENER AND CALCULATION CLASS
class ClearFieldsActionimplements ActionListener
//This clears the fields so the user can enter in new data.
{
publicvoid actionPerformed(ActionEvent e)
{
principalField.setText("");
interestField.setText("");
termField.setText("");
monthlyField.setText("");
displayArea.setText("");
}
}//END ACTIONLISTENER TO CLEAR FIELDS
class ExitProgramActionimplements ActionListener
//Displays a closing message then closes the program
{
publicvoid actionPerformed(ActionEvent e)
{
if (e.getSource() == exitButton)
{
JOptionPane.showMessageDialog(MortgageCalculationsWeek5.this,"Have a great day!","Good-bye",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}//END ACTIONLISTENER FOR EXIT BUTTON
class InterestTermsFile
{
int termFile = 3;
publicvoid InterestTerms()throws IOException
{
int[] term =newint[termFile];
Scanner data =null;
try
{
data =new Scanner(new BufferedReader(new FileReader("Loan Terms.txt")));
int termNumber = 0;
while (data.hasNext())
{
if (data.hasNextInt())
{
term[termNumber++] = data.nextInt();
if (termNumber == termFile)
break;
}
else
{
data.next();
}
}
}
finally
{
/*
I NEED TO FIGURE OUT HOW TO READ THE USER'S SELECTION IN THE COMBO BOX, READ THE FILE, THEN DISPLAY THE AMOUNT FROM THE FILE INTO THE TEXT FIELD
String term1 = (String)term[0];
String term2 = (String)term[1];
String term3 = (String)term[2];
interestField.setText(?);
termField.setText(term[0]);
termField.setText(term[1]);
termField.setText(term[2]);
*/
}
}
}
//THE PIE CHART STUFF IS NOT COMPLETE. WE DID A PIE CHART CODE SEPARATE FIRST. I'M TRYING TO INCORPORATE IT INTO THIS WEEK'S ASSIGNMENT.
publicclass PieChartextends JPanelimplements ActionListener
{
Label inputlabel;
TextField input1, input2;
Button b;
JPanel p =new JPanel();
int number[], degrees[];
public PieChart()
{
number=newint[2];
degrees=newint[2];
input1=new TextField(5);//This would be the principal amount principalField
input2=new TextField(5);//This would be a variable that is created from a calculation of the total interest paid. I still need the calculation for that.
b=new Button("Draw Piechart");
b.addActionListener(this);
add(p, BorderLayout.NORTH);
}
publicvoid actionPerformed(ActionEvent e)
{
if (e.getSource() == b)
{
number[0] = Integer.parseInt(input1.getText());
number[1] = Integer.parseInt(input2.getText());
degrees[0] = number[0] * 360 / (number[0]+number[1]);
degrees[1] = 360 - degrees[0];
Graphics2D g2 = (Graphics2D) getGraphics();
g2.setColor(Color.green);
g2.fillArc(140, 160, 200, 200, 0, degrees[0]);
g2.setColor(Color.blue);
g2.fillArc(140, 160, 200, 200, degrees[0], degrees[1]);
}
}
}
}//end of program
[19723 byte] By [
DaBoujiboa] at [2007-11-27 4:51:21]

Thank you all for your help. I got the pie to display though it still does not display the current figures (I want it to display the total interest paid and total principal paid but that is not a concern of mine right now).
However, the pie chart is a teeny little thing and I don't know why. Can anyone solve this mystery for me? I just don't get why it is so tiny.
I'm only reposting my code since it changed and to answer my follow-up question you will need to see it. I don't feel a new thread is necessary since this is a follow-up to my previous question. There are two files for this to work. I know it is a bit messy.
Thank you again for your help and feedback!
Christy
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.io.*;
import java.util.*;
public class MortgageCalculationsWeek5 extends JPanel
{
//Initialize variables
JFramemainFrame;
JButton calculateButton, clearButton, exitButton, pieButton;
JTextField principalField, interestField, termField, monthlyField, termResult, interestResult, interestPaidField, principalPaidField;
JTextArea displayArea;
JScrollPane displayPane;
JLabel principalLabel, termLabel, interestLabel, interestRateLabel, TermLabel, monthlyLabel, intPaidLabel, priPaidLabel;
JLabelintructionLabel1, intructionLabel2, intructionLabel3, intructionLabel4, intructionLabel5, intructionLabel6;
JPanel mainPanel, buttonPanel, titlePanel, basePanel, piePanel;
JComboBox termCombo, interestCombo;
Pie pie;
String principalString, interestString, termString, interestBox, termYears;
String pie1, pie2;
double principalAmt, loanInterest, loanTerm, monthlyPayment, interestPayment, principalPayment, remainingBalance, months, monthlyInt, totalInterest, totalPrincipal, totalInterestPaid, totalPrincipalPaid;
int[] inputs;
public static void main (String[] args)
{
javax.swing.SwingUtilities.invokeLater(
new Runnable() {
public void run() {
new MortgageCalculationsWeek5();
}
}
);
}
public MortgageCalculationsWeek5()
{
mainFrame = new JFrame();
mainFrame.setSize(900,600);
mainFrame.setLocation(100,0);
mainFrame.setTitle("MORTGAGE CALCULATOR");
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//create panels
mainPanel = new JPanel();
titlePanel = new JPanel();
buttonPanel = new JPanel();
piePanel = new JPanel();
basePanel = new JPanel(new GridLayout(0,1));
//Instruction labels for titlePanel
intructionLabel1 = new JLabel("Instructions:Enter in the principal amount that you want. Next either enter in the interest and term or select from the drop-down lists. After entering");
intructionLabel2 = new JLabel("the data, click on the CALCULATE button to calculate. If you want to enter in different information, click on the CLEAR button to clear the fields and start");
intructionLabel3 = new JLabel("over. When you are done, click on the EXIT button. ");
intructionLabel4 = new JLabel("");
intructionLabel5 = new JLabel("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
//principal label and text field
principalLabel = new JLabel("Principal:");
principalField = new JTextField(10);
interestLabel = new JLabel("Interest Rate (APR):");
String[] InterestRates = {"5.35", "5.50", "5.75"};
interestCombo = new JComboBox(InterestRates);
interestCombo.setEditable(false);
termLabel = new JLabel("Term (in years):");
//term combo box
//WORK ON THE CODE TO READ THE FILE HERE!!!*************************************************************
/*int termFile = 3;
int[] term = new int[termFile];
Scanner data = null;
try
{
data = new Scanner(new BufferedReader(new FileReader("LoanTerms.txt")));
int termNumber = 0;
while (data.hasNext())
{
if (data.hasNextInt())
{
term[termNumber++] = data.nextInt();
if (termNumber == termFile)
break;
}
else
{
data.next();
}
}
}
finally
{
}
int[] TermYears = {term[0], term[1], term[2]};
//PROBLEMS GETTING IT TO READ THE ARRAY CORRECTLY***************************************************
*/String[] TermYears = {"7", "15", "30"};//change this to the array for reading a file
termCombo = new JComboBox(TermYears);
termCombo.setSelectedIndex(0);
termCombo.setEditable(false);
//Monthly Payment label and text field
JLabel addSpace1 = new JLabel("");
JLabel addSpace2 = new JLabel("");
monthlyLabel = new JLabel("Monthly Payment:");
monthlyField = new JTextField(7);
intPaidLabel = new JLabel("Interest Paid:");
interestPaidField = new JTextField(7);
priPaidLabel = new JLabel("Principal Paid:");
principalPaidField = new JTextField(7);
//display area
displayArea = new JTextArea(5,70);
displayArea.setEditable(false);
displayPane = new JScrollPane(displayArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//buttons
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(new CalculateButtonListener());
pieButton = new JButton("Create Pie Chart");
pieButton.addActionListener(new PieButtonListener());
clearButton = new JButton("Clear Selections");
clearButton.addActionListener(new ClearFieldsAction());
exitButton = new JButton("Exit Program");
exitButton.addActionListener(new ExitProgramAction());
pie1 = principalField.getText();
pie2 = monthlyField.getText();
inputs = new int[2];
pie = new Pie(new int[]{1,1});//{} is the array numbers 0 and 1 since we know it is going to start with 0; but if we start with 0, it will only show 1 color
piePanel.add(pie);
//add to titlePanel
titlePanel.add(intructionLabel1);
titlePanel.add(intructionLabel2);
titlePanel.add(intructionLabel3);
titlePanel.add(intructionLabel4);
titlePanel.add(intructionLabel5);
//add to mainPanel
mainPanel.add(addSpace1);
mainPanel.add(principalLabel);
mainPanel.add(principalField);
mainPanel.add(interestLabel);
mainPanel.add(interestCombo);
mainPanel.add(termLabel);
mainPanel.add(termCombo);
mainPanel.add(addSpace2);
mainPanel.add(monthlyLabel);
mainPanel.add(monthlyField);
mainPanel.add(intPaidLabel);
mainPanel.add(interestPaidField);
mainPanel.add(priPaidLabel);
mainPanel.add(principalPaidField);
mainPanel.add(displayPane);
buttonPanel.add(calculateButton);
buttonPanel.add(pieButton);
buttonPanel.add(clearButton);
buttonPanel.add(exitButton);
//add other panels to base
basePanel.add(titlePanel);
basePanel.add(mainPanel);
basePanel.add(buttonPanel);
basePanel.add(piePanel);
//add base panel to frame
mainFrame.setLayout(new GridLayout(0,1));
mainFrame.add(basePanel);
mainFrame.setVisible(true);
}
private void SetTextFunctionMonthly(String text)
{
monthlyField.setText(text);
}
private void SetTextFunctionPrincipal(String text)
{
principalPaidField.setText(text);
}
private void SetTextFunctionInterest(String text)
{
interestPaidField.setText(text);
}
class CalculateButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e) throws NullPointerException
{
principalString = principalField.getText();
interestString = (String)interestCombo.getSelectedItem();
termString = (String)termCombo.getSelectedItem();
//get user input and display exceptions
try
{
principalAmt = Double.parseDouble(principalString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error with the principal entered. Field is either blank or invalid data entered.", "Exception #1", JOptionPane.ERROR_MESSAGE);
principalField.requestFocus();
return;
}
try
{
loanInterest = Double.parseDouble(interestString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error with the interest entered. Field is either blank or invalid data entered.", "Exception #2", JOptionPane.ERROR_MESSAGE);
interestField.requestFocus();
return;
}
try
{
loanTerm = Double.parseDouble(termString);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Error with the term entered. Field is either blank or invalid data entered.", "Exception #3", JOptionPane.ERROR_MESSAGE);
termField.requestFocus();
return;
}
// Display principal, interest, and loan balance of entire term
months = loanTerm * 12;
monthlyInt = (loanInterest / 100) / 12;
monthlyPayment = (principalAmt * monthlyInt) / (1 - Math.pow(1 / (1 + monthlyInt), months));
DecimalFormat decimals2 = new DecimalFormat("0.00");
NumberFormat Currency = NumberFormat.getCurrencyInstance();
SetTextFunctionMonthly("" + decimals2.format(monthlyPayment));
for (int i = 1; i <= months; ++i)
{
interestPayment = principalAmt * monthlyInt;
principalPayment = monthlyPayment - interestPayment;
remainingBalance = principalAmt - principalPayment;
totalInterest = totalInterest += interestPayment;
totalPrincipal += principalPayment;
displayArea.append("\n#" + i + "\t\tP=" + Currency.format(principalPayment) + "\t\tI=" + Currency.format(interestPayment)
+ "\t\tB=" + Currency.format(remainingBalance) + "\n");
principalAmt -= principalPayment; // calculate until payments are done
}
totalInterestPaid = totalInterest += interestPayment;
totalPrincipalPaid = totalPrincipal += principalPayment;
SetTextFunctionInterest("" + decimals2.format(totalInterestPaid));
SetTextFunctionPrincipal("" + decimals2.format(totalPrincipalPaid));
//System.out.println("Total Interest: " + Currency.format(totalInterestPaid) + "\nTotal Principal: "+ Currency.format(totalPrincipalPaid));
}
}//END ACTIONLISTENER AND CALCULATION CLASS
class PieButtonListener extends JPanel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == pieButton)
{
//int[]a = new int[2];
inputs[0] = Integer.parseInt(interestPaidField.getText());
inputs[1] = Integer.parseInt(principalPaidField.getText());
pie.setNumber(inputs);
//pie = new Pie(inputs);
repaint();
}
}
}
class ClearFieldsAction implements ActionListener
//This clears the fields so the user can enter in new data.
{
public void actionPerformed(ActionEvent e)
{
principalField.setText("");
monthlyField.setText("");
displayArea.setText("");
principalField.requestFocus();
}
}//END ACTIONLISTENER TO CLEAR FIELDS
class ExitProgramAction implements ActionListener
//Displays a closing message then closes the program
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitButton)
{
JOptionPane.showMessageDialog(MortgageCalculationsWeek5.this,"Have a great day!","Good-bye",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}//END ACTIONLISTENER FOR EXIT BUTTON
}//end of program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Pie extends JPanel
{
int[] number;
public Pie(int[] a)//constructor of pie chart
{
number = new int[a.length];
for (int i=0; i<a.length; i++)
number[i]=a[i];//will throw a null point exception because this array was not created as an object without line 8
}
public void setNumber(int a[])
{
number = new int[a.length];
for (int i=0; i><a.length; i++)
number[i]=a[i];//will throw a null point exception because this array was not created as an object without line 8
System.out.println();
}
public void paintComponent(Graphics g)
{
int v = getWidth();
int h = getHeight();
int[] degrees = new int[number.length];
int a = 0;
/*for (int i=0; i><number.length; i++)
{
a += number[i];
}
for (int i=0; i><degrees.length; i++)
{
degrees[i]= number[i] / a;
}
g.setColor(Color.green);
g.fillArc(0, 0, v, h, 0, degrees[0]);
for (int i=1; i><degrees.length; i++)
{
g.setColor(Color.blue);
g.fillArc(0, 0, v, h, degrees[i-1], degrees[i]);
}
*/
degrees[0] = number[0] * 360 / (number[0]+number[1]);
degrees[1] = 360 - degrees[0];
g.setColor(Color.green);
g.fillArc(0, 0, v, h, 0, degrees[0]);
g.setColor(Color.blue);
g.fillArc(0, 0, v, h, degrees[0], degrees[1]);
}
}
>