zad1999
asked on
Graphics2D Class
I have a working mortgage program. My task now is to create a graph that will display the yearly interest and yearly principle. This should be a line graph. I have seen several examples on here and I have some good info in my text book. But....my question is what is the best way to add a new JPanel to my existing program. Do I just create a new class , then a method that contains a new JPanel in which the graph is drawn? Using multiple classes confuses me. I'm not looking for anyone to do the coding for me, but just to give me a push in the right direction.
P.S. Do not want to use a 3rd party program, the code needs to be written in Java from scratch. For reference purposes, I have included my existing, working code and attached my text file.
I will try to get started on my own, but doubtful I will make progress quickly.
P.S. Do not want to use a 3rd party program, the code needs to be written in Java from scratch. For reference purposes, I have included my existing, working code and attached my text file.
I will try to get started on my own, but doubtful I will make progress quickly.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.io.BufferedReader;
import java.io.*;
public class MortgageWk5New extends JFrame implements ActionListener
{
//variables
double [] rate;
int[] term;
double r;
double t;
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $",JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField (6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER);//,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%" , false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(" # Interest Principle Balance");
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5New()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder( 10, 10, 10, 10 );
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
row1.setBorder( rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
row2.setBorder( rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6 ));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
row4.setBorder( rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
row5.setBorder( rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
//button.add(amortizeButton);
pane.add(button);
//amortizeButton.setEnabled(false);
button.setMaximumSize( new Dimension( 10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new
InputStreamReader (getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader (fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for(int i = 0; i< line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for(int i = 0; i<line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if(button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if(command == calculateButton)
{
if(button_1.isSelected())
{
r = (rate[0]/100)/12;
t = term[0]*12;
payment();
}
else if(button_2.isSelected())
{
r = (rate[1]/12)/100;
t = term[1]*12;
payment();
}
else if(button_3.isSelected())
{
r = (rate[2]/12)/100;
t = term[2]*12;
payment();
}
else if (button_4.isSelected())
{
paymentText();
}
}
else if(command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if(command == exitButton)
{
System.exit(0);
}
}
public static void main(String[] arguments)
{
MortgageWk5New mortCal = new MortgageWk5New();
mortCal.setSize(550,550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(200,200);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm*12;
moInterest = (userRate/100)/12;
double payment = (principle*moInterest)/(1-Math.pow(1/(1+moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0 || userRate <=0 || userTerm <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = moInterest*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
}
data.txt
You will create a new graphPanel JPanel the same way you created the other JPanels.
ASKER
Will a JFrame work. I added code for one and when I clicked the graph button, a new frame opened, albeit a blank one.
I have added more code for the graph and now it won't compile. I desparately need some advice. I have used code from an example I found and maybe I'm missing some corresponding code, but I don't think so. The compile errors are:
G:\PRG421\MortgageWk5New.j ava:454: ';' expected
String LineMetrics 1m;
^
G:\PRG421\MortgageWk5New.j ava:454: not a statement
String LineMetrics 1m;
^
G:\PRG421\MortgageWk5New.j ava:461: ';' expected
height = 1m.getAscent();
^
G:\PRG421\MortgageWk5New.j ava:484: ';' expected
height = 1m.getheight();
^
G:\PRG421\MortgageWk5New.j ava:517: illegal start of expression
private int[] getDataVals()
^
G:\PRG421\MortgageWk5New.j ava:517: ';' expected
private int[] getDataVals()
^
G:\PRG421\MortgageWk5New.j ava:519: ';' expected
int max = Integer.MIN VALUE;
^
G:\PRG421\MortgageWk5New.j ava:519: not a statement
int max = Integer.MIN VALUE;
^
G:\PRG421\MortgageWk5New.j ava:520: ';' expected
int min = Integer.MAX VALUE;
^
G:\PRG421\MortgageWk5New.j ava:520: not a statement
int min = Integer.MAX VALUE;
I have added more code for the graph and now it won't compile. I desparately need some advice. I have used code from an example I found and maybe I'm missing some corresponding code, but I don't think so. The compile errors are:
G:\PRG421\MortgageWk5New.j
String LineMetrics 1m;
^
G:\PRG421\MortgageWk5New.j
String LineMetrics 1m;
^
G:\PRG421\MortgageWk5New.j
height = 1m.getAscent();
^
G:\PRG421\MortgageWk5New.j
height = 1m.getheight();
^
G:\PRG421\MortgageWk5New.j
private int[] getDataVals()
^
G:\PRG421\MortgageWk5New.j
private int[] getDataVals()
^
G:\PRG421\MortgageWk5New.j
int max = Integer.MIN VALUE;
^
G:\PRG421\MortgageWk5New.j
int max = Integer.MIN VALUE;
^
G:\PRG421\MortgageWk5New.j
int min = Integer.MAX VALUE;
^
G:\PRG421\MortgageWk5New.j
int min = Integer.MAX VALUE;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.geom.*;
import java.awt.Insets;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.io.BufferedReader;
import java.io.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.*;
public class MortgageWk5New extends JFrame implements ActionListener
{
//variables
double [] rate;
int[] term;
double r;
double t;
private float[] yearlyInt;
private float[] yearlyPrin;
private JFrame mFrame = null;
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $",JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField (6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER);//,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%" , false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(" # Interest Principle Balance");
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
JButton graphButton = new JButton("graph");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5New()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder( 10, 10, 10, 10 );
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
row1.setBorder( rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
row2.setBorder( rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6 ));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
row4.setBorder( rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
row5.setBorder( rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
button.add(graphButton);
pane.add(button);
button.setMaximumSize( new Dimension( 10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
graphButton.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new
InputStreamReader (getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader (fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for(int i = 0; i< line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for(int i = 0; i<line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if(button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if(command == calculateButton)
{
if(button_1.isSelected())
{
r = (rate[0]/100)/12;
t = term[0]*12;
payment();
}
else if(button_2.isSelected())
{
r = (rate[1]/12)/100;
t = term[1]*12;
payment();
}
else if(button_3.isSelected())
{
r = (rate[2]/12)/100;
t = term[2]*12;
payment();
}
else if (button_4.isSelected())
{
paymentText();
}
}
else if(command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if(command == exitButton)
{
System.exit(0);
}
else if(command == graphButton)
{
mFrame = new JFrame("Mortgage Graph");
mFrame.getContentPane().add(new graphPanel());
mFrame.setSize(800, 600);
mFrame.setLocation(200,100);
JMenu menuExit = new JMenu ("Exit", true);
menuExit.add(menuExit);
menuExit.add(menuExit);
mFrame.setVisible(true);
menuExit.addActionListener(this);
}
}
public static void main(String[] arguments)
{
MortgageWk5New mortCal = new MortgageWk5New();
mortCal.setSize(550,550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(200,200);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm*12;
moInterest = (userRate/100)/12;
double payment = (principle*moInterest)/(1-Math.pow(1/(1+moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0 || userRate <=0 || userTerm <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = moInterest*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
class graphPanel extends JPanel
{
final int
HPAD = 40,
VPAD = 80;
Font font;
int i = 0;
int [] pData = new int [30];
int iData;
public graphPanel(int [] p, float[] i)
{
for (int p = 20000; p < 620000; p = p + 20000)
{
pData[i] = p;
i++;
}
iData = i;
font = new Font("lucida sans regular", Font.PLAIN, 14);
setBackground(Color.white);
System.out.println(data[3]);//for testing***************REMOVE*******************
}
}
protected void painter (Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//g2.setRenderingHint (RenderingHints.KEY ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
int w = getWidth();
int h = getHeight();
//graph scales
float xInc = (h - 2*VPAD)/30f;
int [] dataVals = getDataVals(); //the minimum and maximum values for the y-axis
float yScale = dataVals[2] / 29f;
//y-axis
g2.draw (new Line2D.Double(HPAD, VPAD, HPAD, H-VPAD));
//Graph tic marks
float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
for (int j = 0; j <=10; j++)
{
g2.draw(new Line2D.Double(x1, y1, x2, y1));
y1 += yInc;
}
//axis labels???????????????????????????/
String text;
String LineMetrics 1m;
float xs, ys, textWidth, height;
for(int i=0; i<=10; i++)
{
text = String.valueOf(dataVals[1] - (int) (i*yScale));
textWidth = (float) font.getStringBounds(text, frc).getWidth();
lm = font.getLineMetrics(text, frc);
height = 1m.getAscent();
xs = HPAD - textWidth - 7;
ys = VPAD + (j*yInc) + height/2;
g2.drawString(text,xs,ys);
//x-axis
g2.draw(new Line2D.Double(HPAD, h - VPAD, w-VPAD, h-VPAD));
//x-axis tic marks
x1 = HPAD; y1=h-VPAD; y2 = y1 +3;
for(int i = 0; i<interestData.length; i++)
{
g2.draw(new Line2D.Double(x1, y1, x1, y2));
x1 += xInc;
}
//Labels
ys = h - VPAD;
for(int j = 0; j<interestData.length; j++)
{
text=String.valueOf(j+1);
textWidth = (float) font.getStringBounds(text, frc).getWidth();
lm = font.getLinemetrics(text,frc);
height = 1m.getheight();
xs = HPAD + j * xInc - textWidth/2;
g2.drawString(text,xs,ys+height);
}
//Plot the data to the graph***I HOPE****
float yy2 = 0, yy1 = 0, xx2=0, xx1;
x1=HPAD;
yScale = (float)(h-2*VPAD)/dataVals[2];
for(int j = 0; j< interestData.length; j++)
{
g.setColor(Color.blue);
y1 = VPAD + (h - 2*VPAD) - (principleData[j] - dataVals[0]) * yScale;
if(j>0)
g2.draw(new Line2D.Double(x1, y1, x2, y2));
x2 = x1;
y2=y1;
x1 += xInc;
g.setColor(Color.green);
yy1 = VPAD + (h-2*VPAD) - (interestData[j] - dataVals[0]) * yScale;
if(j>0)
g2.draw(new Line2D.Double(xx1, yy1, xx2, yy2));
xx2=xx1;
yy2 = yy1;
xx1 += xInc;
}
}
private int[] getDataVals()
{
int max = Integer.MIN VALUE;
int min = Integer.MAX VALUE;
int j = interestData.length-1;
max = (int)principleData[j];
min = (int)interestData[j];
int span = max - min;
return new int[] {min, max, span};
}
}
}
data.txt
ASKER
ok - I took out a bunch of stuff. Here is the last known configuration of my program that will compile. I do not expect, nor do I want, an expert to complete this for me. As mentioned above, I need to know the next step to get this baby working.
I would appreciate some advice. In the meantime, I'm digging the textbooks back out and will be working on this. I will check in frequently to see if any responses have been posted.
I would appreciate some advice. In the meantime, I'm digging the textbooks back out and will be working on this. I will check in frequently to see if any responses have been posted.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.geom.*;
import java.awt.Insets;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.io.BufferedReader;
import java.io.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.*;
public class MortgageWk5New extends JFrame implements ActionListener
{
//variables
double [] rate;
int[] term;
double r;
double t;
private float[] yearlyInt;
private float[] yearlyPrin;
private JFrame mFrame = null;
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $",JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField (6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER);//,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%" , false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(" # Interest Principle Balance");
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
JButton graphButton = new JButton("graph");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5New()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder( 10, 10, 10, 10 );
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
row1.setBorder( rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
row2.setBorder( rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6 ));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
row4.setBorder( rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
row5.setBorder( rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
button.add(graphButton);
pane.add(button);
button.setMaximumSize( new Dimension( 10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
graphButton.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new
InputStreamReader (getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader (fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for(int i = 0; i< line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for(int i = 0; i<line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if(button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if(command == calculateButton)
{
if(button_1.isSelected())
{
r = (rate[0]/100)/12;
t = term[0]*12;
payment();
}
else if(button_2.isSelected())
{
r = (rate[1]/12)/100;
t = term[1]*12;
payment();
}
else if(button_3.isSelected())
{
r = (rate[2]/12)/100;
t = term[2]*12;
payment();
}
else if (button_4.isSelected())
{
paymentText();
}
}
else if(command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if(command == exitButton)
{
System.exit(0);
}
else if(command == graphButton)
{
mFrame = new JFrame("Mortgage Graph");
mFrame.getContentPane().add(new graphPanel());
mFrame.setSize(800, 600);
mFrame.setLocation(200,100);
JMenu menuExit = new JMenu ("Exit", true);
menuExit.add(menuExit);
menuExit.add(menuExit);
mFrame.setVisible(true);
menuExit.addActionListener(this);
}
}
public static void main(String[] arguments)
{
MortgageWk5New mortCal = new MortgageWk5New();
mortCal.setSize(550,550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(200,200);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm*12;
moInterest = (userRate/100)/12;
double payment = (principle*moInterest)/(1-Math.pow(1/(1+moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0 || userRate <=0 || userTerm <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = moInterest*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
class graphPanel extends JPanel
{
final int
HPAD = 40,
VPAD = 80;
Font font;
int i = 0;
int [] data = new int [30];
public graphPanel()
{
for (int p = 20000; p < 620000; p = p + 20000)
{
data[i] = p;
i++;
}
font = new Font("lucida sans regular", Font.PLAIN, 14);
setBackground(Color.white);
System.out.println(data[3]);//for testing***************REMOVE*******************
}
}
}
ASKER
This is as far as I have gotten; and it's not very far. I tried modifying a working program I found on this site, but have it totally messed up. I sure hope someone can tell me what to do next with this.
P.S. the last line "g2.draLine(10,10, 50, 50); probably does nothing, but I was trying to figure out how to get even a simple line to show in the new panel when the graph button is pushed. I was thinking if I could accomplish that small task, I might finally get somewhere with this aggravating assignment that I've already wasted too much time on :-)
P.S. my corresponding sequential file has already been attached in an earlier posting.
P.S. the last line "g2.draLine(10,10, 50, 50); probably does nothing, but I was trying to figure out how to get even a simple line to show in the new panel when the graph button is pushed. I was thinking if I could accomplish that small task, I might finally get somewhere with this aggravating assignment that I've already wasted too much time on :-)
P.S. my corresponding sequential file has already been attached in an earlier posting.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.geom.*;
import java.awt.Insets;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.io.BufferedReader;
import java.io.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.*;
public class MortgageWk5New extends JFrame implements ActionListener
{
//variables
double [] rate;
int[] term;
double r;
double t;
private float[] yearlyInt;
private float[] yearlyPrin;
private JFrame mFrame = null;
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $",JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField (6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER);//,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%" , false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(" # Interest Principle Balance");
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
JButton graphButton = new JButton("graph");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5New()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder( 10, 10, 10, 10 );
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
row1.setBorder( rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
row2.setBorder( rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6 ));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
row4.setBorder( rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
row5.setBorder( rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
button.add(graphButton);
pane.add(button);
button.setMaximumSize( new Dimension( 10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
graphButton.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new
InputStreamReader (getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader (fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for(int i = 0; i< line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for(int i = 0; i<line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if(button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if(command == calculateButton)
{
if(button_1.isSelected())
{
r = (rate[0]/100)/12;
t = term[0]*12;
payment();
}
else if(button_2.isSelected())
{
r = (rate[1]/12)/100;
t = term[1]*12;
payment();
}
else if(button_3.isSelected())
{
r = (rate[2]/12)/100;
t = term[2]*12;
payment();
}
else if (button_4.isSelected())
{
paymentText();
}
}
else if(command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if(command == exitButton)
{
System.exit(0);
}
else if(command == graphButton)
{
mFrame = new JFrame("Mortgage Graph");
mFrame.getContentPane().add(new graphPanel());
mFrame.setSize(800, 600);
mFrame.setLocation(200,100);
JMenu menuExit = new JMenu ("Exit", true);
menuExit.add(menuExit);
menuExit.add(menuExit);
mFrame.setVisible(true);
menuExit.addActionListener(this);
}
}
public static void main(String[] arguments)
{
MortgageWk5New mortCal = new MortgageWk5New();
mortCal.setSize(550,550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(200,200);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm*12;
moInterest = (userRate/100)/12;
double payment = (principle*moInterest)/(1-Math.pow(1/(1+moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0 || userRate <=0 || userTerm <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = moInterest*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
class graphPanel extends JPanel
{
final int
HPAD = 40,
VPAD = 80;
Font font;
int i = 0;
int [] data = new int [30];
public graphPanel()
{
for (int p = 20000; p < 620000; p = p + 20000)
{
data[i] = p;
i++;
}
font = new Font("lucida sans regular", Font.PLAIN, 14);
setBackground(Color.white);
System.out.println(data[3]);//for testing***************REMOVE*******************
}
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine(10,10,50,50);
}
}
ASKER
Well - I have tried this a different way, just to try to get something to work, but I'm obviously still doing something wrong. Program compiles, has errors on first run using Text Pad, then when I run 2nd time, it works, but...........I get a blank window still
Teacher says no 3rd party apps
Please help!!!
see above for attached sequential file to fill arrays
Teacher says no 3rd party apps
Please help!!!
see above for attached sequential file to fill arrays
//import java.awt.Container;
//import java.awt.Dimension;
import java.awt.geom.*;
//import java.awt.Insets;
//import java.awt.FlowLayout;
//import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
//import javax.swing.BoxLayout;
//import javax.swing.ButtonGroup;
//import javax.swing.JButton;
//import javax.swing.JFrame;
//import javax.swing.JLabel;
//import javax.swing.JOptionPane;
//import javax.swing.JPanel;
//import javax.swing.JRadioButton;
//import javax.swing.JScrollPane;
//import javax.swing.JTextArea;
//import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
//import java.io.BufferedReader;
import java.io.*;
//import java.awt.font.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.*;
import java.awt.Graphics2D;
//import java.awt.geom.Line2D;
public class MortgageWk5NewC extends JFrame implements ActionListener
{
//variables
double [] rate;
int[] term;
double r;
double t;
private float[] yearlyInt;
private float[] yearlyPrin;
private JFrame mFrame = null;
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $",JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField (6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER);//,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%" , false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(" # Interest Principle Balance");
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
JButton graphButton = new JButton("graph");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5NewC()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder( 10, 10, 10, 10 );
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
row1.setBorder( rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
row2.setBorder( rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6 ));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
row4.setBorder( rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
row5.setBorder( rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
button.add(graphButton);
pane.add(button);
button.setMaximumSize( new Dimension( 10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
graphButton.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new
InputStreamReader (getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader (fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for(int i = 0; i< line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for(int i = 0; i<line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if(button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if(command == calculateButton)
{
if(button_1.isSelected())
{
r = (rate[0]/100)/12;
t = term[0]*12;
payment();
}
else if(button_2.isSelected())
{
r = (rate[1]/12)/100;
t = term[1]*12;
payment();
}
else if(button_3.isSelected())
{
r = (rate[2]/12)/100;
t = term[2]*12;
payment();
}
else if (button_4.isSelected())
{
paymentText();
}
}
else if(command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if(command == exitButton)
{
System.exit(0);
}
else if(command == graphButton)
{
getContentPane().add(new ChartPanel());
setSize(300,300);
show();
}
}
public static void main(String[] arguments)
{
MortgageWk5New mortCal = new MortgageWk5New();
mortCal.setSize(550,550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(200,200);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm*12;
moInterest = (userRate/100)/12;
double payment = (principle*moInterest)/(1-Math.pow(1/(1+moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat ("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if(principle <=0 || userRate <=0 || userTerm <=0) throw new NumberFormatException();//does not allow 0 or null value to be entered
else done = true;
displayArea.setText(null);
//amortization variables
int payNum=0;
while(principle>0.001)
{
//variables for amortiztion
payNum = payNum+1;
double pdInt = moInterest*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " +twoDigits.format(pdInt) + " " + twoDigits.format(pdPrince) + " " + twoDigits.format(loanBal)+"\n");
displayArea.setCaretPosition(0);
}
}
catch(NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR", JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
}
class ChartPanel extends JPanel
{
public void paintComponent (Graphics comp)
{
super.paintComponent(comp);
Dimension size = getSize();
Graphics2D comp2D = (Graphics2D)comp;
BasicStroke pen = new BasicStroke (1F);
comp2D.setStroke(pen);
float insets = 10f;
float xLegend = 35f;
float xStart = insets + xLegend;
float xEnd = size.width - insets;
float yStart = size.height - insets;
float yEnd = insets;
comp2D.setColor(Color.blue);
Line2D hLn = new Line2D.Float(xStart, yStart, xEnd, yStart);
comp2D.draw(hLn);
Line2D vLn = new Line2D.Float(xStart, yStart, xStart, yEnd);
comp2D.draw(vLn);
Font chartFont = new Font ("Dialog", Font.BOLD, 10);
comp2D.setFont(chartFont);
comp2D.setColor(Color.red);
comp2D.drawString("0.00", (float) (xStart - xLegend), (float)yStart);
comp2D.setColor(Color.blue);
float idy = yStart;
float yLast = yStart;
float xLast = yStart;
for (float idx = xStart; idx <= xEnd; idx +=10)
{
hLn = new Line2D.Float(xLast, yLast, idx, idy);
comp2D.draw(hLn);
xLast = idx;
yLast = idy;
idy = (float)Math.abs(Math.random()) *(size.height - 2*insets);
}
}
}
Have you resolved this problem? Or do you still require assistance?
ASKER
Yes, I desparately need assistance. I could not get a graph to work in my program, so I decided to start smaller and posted the other question just to try to get a simple line to display; nothing works. I thought I was getting the hang of this Java stuff, but the graph is way over my head.
I have looked at numerous examples on this site, but cannot figure how to incorporate any of them into my program :-(
I would very much appreciate any help/advice/assistance you can provide.
I have looked at numerous examples on this site, but cannot figure how to incorporate any of them into my program :-(
I would very much appreciate any help/advice/assistance you can provide.
Yes, custom graphing can be quite tedious. Attached is an example Graph class I've coded for you.
And an example of us:
Graph graph=new Graph("My graph", 600, 400, 0, 50, 0, 100, new int[]{0, 10, 20, 30, 40, 50}, new int[]{10, 1, 72, 50, 91, 35}, "X axis", "Y axis");
graph.setVisible(true);
Hope that helps.
And an example of us:
Graph graph=new Graph("My graph", 600, 400, 0, 50, 0, 100, new int[]{0, 10, 20, 30, 40, 50}, new int[]{10, 1, 72, 50, 91, 35}, "X axis", "Y axis");
graph.setVisible(true);
Hope that helps.
import javax.swing.*;
import java.awt.*;
public class Graph extends JFrame
{
public int w, h, x_start, x_end, y_start, y_end;
public int [] y, x;
public String x_label, y_label;
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[])
{
super(title);
this.w=w;
this.h=h;
this.x_start=x_start;
this.x_end=x_end;
this.y_start=y_start;
this.y_end=y_end;
this.x=x;
this.y=y;
x_label="";
y_label="";
setLayout(new BorderLayout());
add(new Display(), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);//centres the frame
}
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[], String x_label, String y_label)
{
super(title);
this.w=w;
this.h=h;
this.x_start=x_start;
this.x_end=x_end;
this.y_start=y_start;
this.y_end=y_end;
this.x=x;
this.y=y;
this.x_label=x_label;
this.y_label=y_label;
setLayout(new BorderLayout());
add(new Display(), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);//centres the frame
}
class Display extends JComponent
{
private static final int INSET=40; // this is the margin around the graph
private FontMetrics fm=null;
private Font f=new Font("verdana",Font.PLAIN,9);
public Display()
{
setPreferredSize(new Dimension(w,h));
fm=getFontMetrics(f);
}
public void paintComponent(Graphics gg)
{
super.paintComponent(gg);
Graphics2D g=(Graphics2D)gg;
//make the background white
g.setColor(Color.WHITE);
g.fillRect(0,0,w,h);
//turn on antialising, etc
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
BasicStroke pen = new BasicStroke (1F);
g.setStroke(pen);
g.setFont(f);
int gw=w-2*INSET;
int gh=h-2*INSET;
//draw the axis
g.setColor(Color.BLACK);
g.drawLine(INSET,INSET,INSET,h-INSET);
g.drawLine(INSET,h-INSET,w-INSET,h-INSET);
//label the abscissa
g.setColor(new Color(0x555555));
g.drawString(x_label,w/2-fm.stringWidth(x_label)/2,h-INSET+5+fm.getHeight()*2);
g.setColor(Color.BLACK);
for(int i=0; i<x.length; i++)
{
if(x[i]<=x_end && x[i]>=x_start)
{
int X=INSET+(int)((double)(x[i]-x_start)/x_end*gw);
g.drawLine(X,h-INSET,X,h-INSET+2);
g.drawString(""+x[i], X-fm.stringWidth(""+x[i])/2, h-INSET+fm.getHeight()+3);
}//else, do nothing
}
//label the ordinate
//writing the text label y_label will be a little tricky, so I'll let you figure it
for(int j=0; j<y.length; j++)
{
if(y[j]<=y_end && y[j]>=y_start)
{
int Y=h-INSET-(int)((double)(y[j]-y_start)/y_end*gh);
g.drawLine(INSET-2,Y,INSET,Y);
g.drawString(""+y[j], INSET-2-fm.stringWidth(""+y[j]), Y+fm.getHeight()/2);
}//else, do nothing
}
int preX=x_start-1, preY=0;
//now plot the data
for(int i=0; i<x.length; i++)
{
if(x[i]<=x_end && x[i]>=x_start && y[i]<=y_end && y[i]>=y_start)
{
int X=INSET+(int)((double)(x[i]-x_start)/x_end*gw);
int Y=h-INSET-(int)((double)(y[i]-y_start)/y_end*gh);
if(preX>x_start)
{
//join them up
g.setColor(new Color(0x555555));
g.drawLine(preX,preY,X,Y);
}
g.setColor(Color.BLUE);
g.drawRect(X-2,Y-2,4,4);
preX=X;
preY=Y;
}//else, do nothing
}
}
}
}
I didn't plan it however, and so you'll want to make some alterations to it:
i) The numbers on the axis correspond go the data points; but if two points are close together, then their labels will overlap. So it's probably best to alter it so that it places labels of constant intervals along each axis (as is the case with most graphs anyway).
ii) If you wish it to display the label for the y-axis (ordinate), then you'll need to implement that yourself. A suggestion: render the label to a BufferedImage, rotate the image, and then render the result onto your graph. Alternatively, render each letter from the label one above the other, vertically down.
iii) If you wish for there to be negative values on the ordinate, then you'll need to adjust it so that the x-axis (abscissa) is rendered at the position corresponding to y=0 (shouldn't be too hard).
I'm too lazy to do these myself right now, but if you get stuck on any, then I'll give you a hand when I get a spare moment
i) The numbers on the axis correspond go the data points; but if two points are close together, then their labels will overlap. So it's probably best to alter it so that it places labels of constant intervals along each axis (as is the case with most graphs anyway).
ii) If you wish it to display the label for the y-axis (ordinate), then you'll need to implement that yourself. A suggestion: render the label to a BufferedImage, rotate the image, and then render the result onto your graph. Alternatively, render each letter from the label one above the other, vertically down.
iii) If you wish for there to be negative values on the ordinate, then you'll need to adjust it so that the x-axis (abscissa) is rendered at the position corresponding to y=0 (shouldn't be too hard).
I'm too lazy to do these myself right now, but if you get stuck on any, then I'll give you a hand when I get a spare moment
Oh yeah, a tip: to help with the layout of your code, use a Java IDE (Integrated Development Environment) such as Eclipse[1] or JCreator[2] (both are free). They automatically indent your code, highlight errors, provide auto-completion, et al. All professional programmers use these (or something similar). And they're easy to setup and get started with.
(Also, attached is a screenshot of the result.)
[1] "Eclipse IDE for Java Developers": http://www.eclipse.org/downloads/
[2] http://www.jcreator.com/
graph.jpg
(Also, attached is a screenshot of the result.)
[1] "Eclipse IDE for Java Developers": http://www.eclipse.org/downloads/
[2] http://www.jcreator.com/
graph.jpg
ASKER
a couple questions:
1. You have public graph method twice in your code; is that correct
2. As I incorporate into my code, I should not use the word "public" for the public class Graph extends JFrame class???
I will try to work this into my code; those darned brackets keep messing me up. I think I will try eclipse.
1. You have public graph method twice in your code; is that correct
2. As I incorporate into my code, I should not use the word "public" for the public class Graph extends JFrame class???
I will try to work this into my code; those darned brackets keep messing me up. I think I will try eclipse.
1. The Graph 'method's are actually the constructors; the difference between them resides in the arguments to them. The second one accepts labels for the x- and y-axis, whereas the first does not. This makes the labelling optional.
2. That's correct, unless you place the Graph class into its own Graph.java file (but in the same folder).
2. That's correct, unless you place the Graph class into its own Graph.java file (but in the same folder).
I feel I should elaborate on the above. This is stuff you do need to know, but I've written more than I expected, so read it when you can spare some time.
1. First, method overloading:
You can 'overload' methods, which means that you can define multiple methods of the same name, as long as the JRE (Java Runtime Environment) can distinguish between them, based on the arguments given to each. As an example:
public void output_a_message(String message)
{
System.out.println(message );
}
public void output_a_message()
{
System.out.println("Hello world");
}
now if you call
output_a_message();
then this will obviously call the second instance, and it will display "Hello world".
This is a very useful feature (available in most higher level programming languages).
Secondly, constructors:
There exist a special type of method in Java, called the constructor. This is the 'method' which is called when you create an instance of a class. For example:
public class Example
{
public Example()
{
// this is the constructor
}
}
They have two characteristics which allow you to identify them:
- they have the same name as the class
- they have no return type
(An alternative way of looking at them is that they have a return type of the class, but don't have a method name).
So when you do this:
Example ex = new Example();
it will not only produce an instance of the Example class, but will also run the code in the constructor.
Just like other methods, a constructor can accept arguments. So altering the above class:
public class Example
{
public Example(String arg1)
{
//do something with arg1
}
}
So now, in order to instantiate Example, you must pass a String argument to it:
Example ex = new Example("some argument");
We can also overload constructors, viz.
public class Example
{
public Example()
{
//here's one constructor
}
public Example(String arg1)
{
//here's another constructor
}
public Example(Integer in)
{
//and another
}
}
Which is exactly what I done in my code with the Graph constructor; notice the difference in arguments:
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[])
{ ... }
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[], String x_label, String y_label)
{ ... }
2. As you may already know, rather than putting a multitude of classes into a single file, you can create a new .java file for each class. But in order to do so, the classes must all be 'public', and all need to be in the same folder as each other. (Whereas if you place additional classes into a file, then they must not be defined public).
Placing classes into their own files is not too important if you have only two or three classes (although it is good coding practice), but when you start working on larger projects involving more than a few (sometimes hundreds) of classes, then it becomes essential.
(You'll find yourself doing this more so when you start using Eclipse ;))
1. First, method overloading:
You can 'overload' methods, which means that you can define multiple methods of the same name, as long as the JRE (Java Runtime Environment) can distinguish between them, based on the arguments given to each. As an example:
public void output_a_message(String message)
{
System.out.println(message
}
public void output_a_message()
{
System.out.println("Hello world");
}
now if you call
output_a_message();
then this will obviously call the second instance, and it will display "Hello world".
This is a very useful feature (available in most higher level programming languages).
Secondly, constructors:
There exist a special type of method in Java, called the constructor. This is the 'method' which is called when you create an instance of a class. For example:
public class Example
{
public Example()
{
// this is the constructor
}
}
They have two characteristics which allow you to identify them:
- they have the same name as the class
- they have no return type
(An alternative way of looking at them is that they have a return type of the class, but don't have a method name).
So when you do this:
Example ex = new Example();
it will not only produce an instance of the Example class, but will also run the code in the constructor.
Just like other methods, a constructor can accept arguments. So altering the above class:
public class Example
{
public Example(String arg1)
{
//do something with arg1
}
}
So now, in order to instantiate Example, you must pass a String argument to it:
Example ex = new Example("some argument");
We can also overload constructors, viz.
public class Example
{
public Example()
{
//here's one constructor
}
public Example(String arg1)
{
//here's another constructor
}
public Example(Integer in)
{
//and another
}
}
Which is exactly what I done in my code with the Graph constructor; notice the difference in arguments:
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[])
{ ... }
public Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[], String x_label, String y_label)
{ ... }
2. As you may already know, rather than putting a multitude of classes into a single file, you can create a new .java file for each class. But in order to do so, the classes must all be 'public', and all need to be in the same folder as each other. (Whereas if you place additional classes into a file, then they must not be defined public).
Placing classes into their own files is not too important if you have only two or three classes (although it is good coding practice), but when you start working on larger projects involving more than a few (sometimes hundreds) of classes, then it becomes essential.
(You'll find yourself doing this more so when you start using Eclipse ;))
ASKER
Ok - I was able to successfully incorporate code and get program to compile. However, nothing displays in the window when the graph button is clicked. I will keep playing, but when/if you have time, can you take a look? See if I'm missing something? I have probably been staring at this way too long and nothing is making much sense right now.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.geom.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.io.BufferedReader;
import java.io.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
import java.text.NumberFormat;
public class MortgageWk5NewE extends JFrame implements ActionListener
{
//variables
double[] rate;
int[] term;
double r;
double t;
private float[] yearInterest;
private float[] yearPrinciple;
JMenuItem mnuExit = new JMenuItem("Exit");
JPanel row1 = new JPanel();
JLabel programLabel = new JLabel("MORTGAGE PAYMENT CALCULATOR", JLabel.CENTER);
JPanel row2 = new JPanel(new GridLayout(1, 1));
JLabel loanLabel = new JLabel("Please Enter the Loan Amount: $", JLabel.LEFT);
JTextField loanText = new JTextField(10);
JPanel row3 = new JPanel(new GridLayout(3, 2));
JLabel rateLabel = new JLabel("Enter Finance Rate", JLabel.CENTER);
JTextField rateText = new JTextField(6);
JLabel termLabel = new JLabel("Enter Mortgage Term (Yrs)", JLabel.CENTER); //,JLabel.LEFT);
JTextField termText = new JTextField(10);
JPanel row4 = new JPanel(new GridLayout(1, 2));
JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
JPanel radioPanel = new JPanel(new FlowLayout());
JRadioButton button_1 = new JRadioButton("7 Years at 5.35%", false);
JRadioButton button_2 = new JRadioButton("15 Years at 5.50%", false);
JRadioButton button_3 = new JRadioButton("30 Years at 5.75%", false);
JRadioButton button_4 = new JRadioButton("Enter My Own", false);
JPanel row5 = new JPanel(new GridLayout(1, 2));
JLabel displayPayment = new JLabel(
" # Interest Principle Balance");
JPanel row6 = new JPanel(new GridLayout(5, 30));
JTable table;
DefaultTableModel model; //table for amortization
//***************create buttons***************
JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
JButton calculateButton = new JButton("Calculate");
JButton graphButton = new JButton("graph");
//***************set textarea to diplay payments***************
JTextArea displayArea = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(displayArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//method to construct GUI
public MortgageWk5NewE()
{
setSize(60, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
Border rowborder = new EmptyBorder(10, 10, 10, 10);
pane.add(row1);
row1.add(programLabel);
row1.setMaximumSize(new Dimension(10000, row1.getMinimumSize().height));
row1.setBorder(rowborder);
pane.add(row2);
row2.add(loanLabel);
row2.add(loanText);
row2.setMaximumSize(new Dimension(10000, row2.getMinimumSize().height));
row2.setBorder(rowborder);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(button_1);
bgroup.add(button_2);
bgroup.add(button_3);
bgroup.add(button_4);
radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6));
radioPanel.add(button_1);
radioPanel.add(button_2);
radioPanel.add(button_3);
radioPanel.add(button_4);
pane.add(radioPanel);
Border titledRadioBorder = BorderFactory.createTitledBorder("Please Make a Selection");
radioPanel.setMaximumSize(new Dimension(10000, radioPanel.getMinimumSize().height));
radioPanel.setBorder(titledRadioBorder);
pane.add(row3);
row3.add(rateLabel);
row3.add(rateText);
rateText.setEnabled(false);
row3.add(termLabel);
row3.add(termText);
termText.setEnabled(false);
row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
row3.setBorder(rowborder);
pane.add(row4);
row4.add(paymentLabel);
row4.setMaximumSize(new Dimension(10000, row4.getMinimumSize().height));
row4.setBorder(rowborder);
pane.add(row5);
//row5.add(paymentLabel);
row5.add(displayPayment);
// payment_txt.setEnabled(false); //set payment amount uneditable
row5.setMaximumSize(new Dimension(10000, row5.getMinimumSize().height));
row5.setBorder(rowborder);
// pane.add(row6);
// row6.add(table);
// row6.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
// row6.setBorder(rowborder);
scroll.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
pane.add(scroll);
button.add(calculateButton);
button.add(clearButton);
button.add(exitButton);
button.add(graphButton);
pane.add(button);
button.setMaximumSize(new Dimension(10000, button.getMinimumSize().height));
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
setVisible(true);
setContentPane(pane);
//column names for table
// String[] columnNames = {"Year", "Interest", "Principle", "Balance"};
//model = new DefaultTableModel(columnNames, 0);
//table = new JTable(model);
//JScrollPane scroll_a = new JScrollPane(table);
//table.setPreferredScrollableViewportSize(new Dimension (10,600));
//pane.add(scroll_a);
//***************add listeners***************
clearButton.addActionListener(this);
exitButton.addActionListener(this);
calculateButton.addActionListener(this);
button_1.addActionListener(this);
button_2.addActionListener(this);
button_3.addActionListener(this);
button_4.addActionListener(this);
graphButton.addActionListener(this);
fillArrays();//call method to fill arrays
}
//Fill arrays from sequential file
public void fillArrays()
{
Reader fileInputStream;
try
{
fileInputStream = new InputStreamReader(getClass().getResourceAsStream("data.txt"));
BufferedReader reader = new BufferedReader(fileInputStream);
String[] line = reader.readLine().split(",");
term = new int[line.length];
for (int i = 0; i < line.length; i++)
{
term[i] = Integer.parseInt(line[i].trim());
}
line = reader.readLine().split(",");
rate = new double[line.length];
for (int i = 0; i < line.length; i++)
{
rate[i] = Double.parseDouble(line[i].trim());
}
reader.close();
fileInputStream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
//method to perform actions depending on which radio button is selected
public void actionPerformed(ActionEvent e)
{
if (button_4.isSelected())
{
rateText.setEnabled(true);
termText.setEnabled(true);
}
Object command = e.getSource();
if (command == calculateButton)
{
if (button_1.isSelected())
{
r = (rate[0] / 100) / 12;
t = term[0] * 12;
payment();
} else if (button_2.isSelected())
{
r = (rate[1] / 12) / 100;
t = term[1] * 12;
payment();
}
else if (button_3.isSelected())
{
r = (rate[2] / 12) / 100;
t = term[2] * 12;
payment();
} else if (button_4.isSelected())
{
paymentText();
}
}
else if (command == clearButton)
{
loanText.setText(null);
paymentLabel.setText("Click the calculate button to see payment amount and amortization");
displayArea.setText(null);
rateText.setText(null);
termText.setText(null);
rateText.setEnabled(false);
termText.setEnabled(false);
}
else if (command == exitButton)
{
System.exit(0);
} else if (command == graphButton)
{
mFrame = new JFrame("Mortgage Graph");
mFrame.getContentPane().add(new Graph());
mFrame.setSize(800, 600);
mFrame.setLocation(200, 100);
JMenuBar mnuBar = new JMenuBar();
mFrame.setJMenuBar(mnuBar);
JMenu mnuExitbar = new JMenu("Exit", true);
mnuBar.add(mnuExitbar);
mnuExitbar.add(mnuExit);
mFrame.setVisible(true);
mnuExit.addActionListener(this);
}
}
public JFrame mFrame = new JFrame();
void exitGraph()
{
mFrame.dispose();
mFrame = null;
}
public static void main(String[] arguments)
{
MortgageWk5NewE mortCal = new MortgageWk5NewE();
mortCal.setSize(550, 550);
mortCal.setTitle("Michelle's Mortgage Payment Calculator");
mortCal.setResizable(false);
mortCal.setLocation(0,0);
mortCal.setVisible(true);
}
public void payment()
{
boolean done = false;
try
{
double principle = Double.parseDouble(loanText.getText());
double payment = (principle * r) / (1 - Math.pow(1 / (1 + r), t));
//arrays to store yearly interest/principle
//yearPrinciple = new float [(int)t];
//yearInterest = new float [(int)t];
DecimalFormat twoDigits = new DecimalFormat("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
//for (int i = 0; i <t; i++)
//{
// yearInterest[i] = 0.0f;
// yearPrinciple[i] = 0.0f;
// for(int j = 1; j<=12; j++)
// {
if (principle <= 0)
throw new NumberFormatException();//does not allow 0 or null value to be entered
else
done = true;
displayArea.setText(null);
//amortization variables
int payNum = 0;
while (principle > 0.001)
{
//variables for amortiztion
payNum = payNum + 1;
double pdInt = r * principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " + twoDigits.format(pdInt)
+ " " + twoDigits.format(pdPrince)
+ " " + twoDigits.format(loanBal) + "\n");
displayArea.setCaretPosition(0);
}
} catch (NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null, "Please Enter a Valid Loan Amount (>0)!", "ERROR",
JOptionPane.INFORMATION_MESSAGE);
paymentLabel.setText("**WARNING** - Please input a valid Loan Amount");
}
/*
Thread thisThread = Thread.currentThread();
NumberFormat currency = NumberFormat.getCurrencyInstance();
try
{
double principle = Double.parseDouble(loanText.getText());
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Please enter an amount >0", "Message Dialog", JOptionPane.ERROR_MESSAGE);
}
double principle = Double.parseDouble(loanText.getText());
double payment = (principle*r)/(1-Math.pow(1/(1+r), t));
//arrays to store yearly interest/principle
yearPrinciple = new float [(int)t];
yearInterest = new float [(int)t];
paymentLabel.setText("Your Monthly Payment Amount is: " + currency.format(payment));
for(int i = 0; i<t; i++)
{
yearInterest[i] = 0.0f;
yearPrinciple[i] = 0.0f;
for(int j=1; j<=12; j++)
{
double pdInt = r*principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
yearInterest[i] += pdInt;//interest accumulation
yearPrinciple[i] += pdPrince;//principle accumulation
model.addRow(new Object[] {Integer.toString((i*12)+j), currency.format(payment), currency.format(pdInt), currency.format(pdPrince)});
}
}
*/
}
public void paymentText()
{
boolean done = false;
double moInterest;
try
{
double principle = Double.parseDouble(loanText.getText());
double userRate = Double.parseDouble(rateText.getText());
double userTerm = Double.parseDouble(termText.getText());
userTerm = userTerm * 12;
moInterest = (userRate / 100) / 12;
double payment = (principle * moInterest)
/ (1 - Math.pow(1 / (1 + moInterest), userTerm));
DecimalFormat twoDigits = new DecimalFormat("$###,###,000.00");
paymentLabel.setText("Your Monthly Payment Amount is: " + twoDigits.format(payment));
if (principle <= 0 || userRate <= 0 || userTerm <= 0)
throw new NumberFormatException();//does not allow 0 or null value to be entered
else
done = true;
displayArea.setText(null);
//amortization variables
int payNum = 0;
while (principle > 0.001)
{
//variables for amortiztion
payNum = payNum + 1;
double pdInt = moInterest * principle;
double pdPrince = payment - pdInt;
double loanBal = principle - pdPrince;
principle = loanBal;
//displays amortization table
displayArea.append(payNum + " " + twoDigits.format(pdInt)
+ " " + twoDigits.format(pdPrince)
+ " " + twoDigits.format(loanBal) + "\n");
displayArea.setCaretPosition(0);
}
} catch (NumberFormatException f)
{
//catch null exception
JOptionPane.showMessageDialog(null,
"Please Enter a Valid Amount Loan Amount, Rate, & Term!", "ERROR",
JOptionPane.INFORMATION_MESSAGE);
paymentLabel
.setText("**WARNING** - Please Input a Valid Amount for Loan, Rate, & Term");
}
}
class Graph extends JPanel
{
final int HPAD = 40, VPAD = 80;//********DO I NEED TO DELETE THIS AND THE THREE LINES BELOW?************
Font font;
int i = 0;
int[] data = new int[30];
public int w, h, x_start, x_end, y_start, y_end;
public int [] y, x;
public String x_label, y_label;
public void Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[])
{
//super("TEST");
this.w=w;
this.h=h;
this.x_start=x_start;
this.x_end=x_end;
this.y_start=y_start;
this.y_end=y_end;
this.x=x;
this.y=y;
x_label="";
y_label="";
setLayout(new BorderLayout());
add(new Display(), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);//centres the frame
}
public void Graph(String title, int w, int h, int x_start, int x_end, int y_start, int y_end, int x[], int y[], String x_label, String y_label)
{
//super(title);
this.w=w;
this.h=h;
this.x_start=x_start;
this.x_end=x_end;
this.y_start=y_start;
this.y_end=y_end;
this.x=x;
this.y=y;
this.x_label=x_label;
this.y_label=y_label;
setLayout(new BorderLayout());
add(new Display(), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);//centres the frame
}
class Display extends JComponent
{
private static final int INSET=40; // this is the margin around the graph
private FontMetrics fm=null;
private Font f=new Font("verdana",Font.PLAIN,9);
public Display()
{
setPreferredSize(new Dimension(w,h));
fm=getFontMetrics(f);
}
public void paintComponent(Graphics gg)
{
super.paintComponent(gg);
Graphics2D g=(Graphics2D)gg;
//make the background white
g.setColor(Color.WHITE);
g.fillRect(0,0,w,h);
//turn on antialising, etc
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
BasicStroke pen = new BasicStroke (1F);
g.setStroke(pen);
g.setFont(f);
int gw=w-2*INSET;
int gh=h-2*INSET;
//draw the axis
g.setColor(Color.BLACK);
g.drawLine(INSET,INSET,INSET,h-INSET);
g.drawLine(INSET,h-INSET,w-INSET,h-INSET);
//label the abscissa
g.setColor(new Color(0x555555));
g.drawString(x_label,w/2-fm.stringWidth(x_label)/2,h-INSET+5+fm.getHeight()*2);
g.setColor(Color.BLACK);
for(int i=0; i<x.length; i++)
{
if(x[i]<=x_end && x[i]>=x_start)
{
int X=INSET+(int)((double)(x[i]-x_start)/x_end*gw);
g.drawLine(X,h-INSET,X,h-INSET+2);
g.drawString(""+x[i], X-fm.stringWidth(""+x[i])/2, h-INSET+fm.getHeight()+3);
}//else, do nothing
}
//label the ordinate
//writing the text label y_label will be a little tricky, so I'll let you figure it
for(int j=0; j<y.length; j++)
{
if(y[j]<=y_end && y[j]>=y_start)
{
int Y=h-INSET-(int)((double)(y[j]-y_start)/y_end*gh);
g.drawLine(INSET-2,Y,INSET,Y);
g.drawString(""+y[j], INSET-2-fm.stringWidth(""+y[j]), Y+fm.getHeight()/2);
}//else, do nothing
}
int preX=x_start-1, preY=0;
//now plot the data
for(int i=0; i<x.length; i++)
{
if(x[i]<=x_end && x[i]>=x_start && y[i]<=y_end && y[i]>=y_start)
{
int X=INSET+(int)((double)(x[i]-x_start)/x_end*gw);
int Y=h-INSET-(int)((double)(y[i]-y_start)/y_end*gh);
if(preX>x_start)
{
//join them up
g.setColor(new Color(0x555555));
g.drawLine(preX,preY,X,Y);
}
g.setColor(Color.BLUE);
g.drawRect(X-2,Y-2,4,4);
preX=X;
preY=Y;
}//else, do nothing
}
}
}
}
}
ASKER
This is so involved, I figured I'd better increase points; no idea what the norm is as far as how points equate to complexity. To me, my code is very complex, but to you experts, it's probably child's play :-)
ASKER
Thanks for the advice; it's very good. I read it through and will likely read it several more times. I had no idea I could use the same method name as long as they had different arguments. I did consider trying to use the class in another file, but since this is the last week of class, I will have no more code added.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
<All you need to do now, is retrieve the data that you need to plot, and pass it to the Graph() instance.>
Ok - I think I can handle that. Thanks again for all your wonderful help!!
Ok - I think I can handle that. Thanks again for all your wonderful help!!
ASKER
Very gracious in helping me understand what he did and why he did it which helps to better understand Java.
You're welcome. By the way, when you call the Graph constructor:
The x_start variable is the starting x value along the x-axis. You'd usually set this to 0.
The x_end variable is what the x values are plotted up to. (So x_end-x_start is the 'range').
Similarly for y_start and y_end.
Then the x[] and y[] array variables must be of the same size; where the i-th element of x corresponds to the i-th elements of y.
So if you have the three points (1,2), (5,6), (4,2) then:
x = new int[]{1, 5, 4};
y = new int[]{2, 6, 2};
Good luck
The x_start variable is the starting x value along the x-axis. You'd usually set this to 0.
The x_end variable is what the x values are plotted up to. (So x_end-x_start is the 'range').
Similarly for y_start and y_end.
Then the x[] and y[] array variables must be of the same size; where the i-th element of x corresponds to the i-th elements of y.
So if you have the three points (1,2), (5,6), (4,2) then:
x = new int[]{1, 5, 4};
y = new int[]{2, 6, 2};
Good luck
ASKER
You know, I just had a thought as I'm trying to work through getting my data to the graph...........what to I do since my values are doubles???
Oh, I just spotted your comment now; hopefully you've figured it by now, but if not: you change all of the data variables to type double, and then when you calculate the coordinates for the screen, cast them to type integer before (or as) you hand them to the drawLine/etc methods.