8 Replies - 1721 Views - Last Post: 20 May 2011 - 07:28 AM Rate Topic: -----

#1 aprsr1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 20-February 10

I cannot get my graph to show up

Posted 18 May 2011 - 05:57 PM

I have written a mortgage program for a class and cannot get my graph to show up. Can anyone tell me where I have gone wrong? Thanks for any help in advance!

import javax.swing.JFrame;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.channels.FileChannel;

import static java.lang.Math.min;

/*
PRG/421 Week 3 Assignment: Mortgage Calculator
 
Author: Jim White
 
Date: May 9, 2011
 
Filename: CalcViewer

This is the mortgage loan program
*/

public class CalcViewer {

	public static void main(String[] args) {
	
		JFrame frame = new CalcFrame();								//Calls the CalcFrame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	//Sets the close operation
		//frame.pack();
		frame.setVisible(true);											//Sets the window to visible
		
		/*The following creates a text file that contains the interest rate and years
		I thought it would be best create the file and close the channel before the 
		program actually started*/

		double[] rateyear = new double[6]; // Array to store rateyear
		rateyear[0] = 5.35; // Seed the first prime
		rateyear[1] = 5.5; // and the second
		rateyear[2] = 5.75;
		rateyear[3] = 7;
		rateyear[4] = 15;
		rateyear[5] = 30;

		File aFile = new File("interestRates.txt");
		FileOutputStream outputFile = null;
		try {
			outputFile = new FileOutputStream(aFile); // Create the file stream
		} catch (FileNotFoundException e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}
		FileChannel file = outputFile.getChannel(); // Get the channel from the stream
		final int BUFFERSIZE = (8*rateyear.length); // Byte buffer size
		ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
		DoubleBuffer doubleBuf = buf.asDoubleBuffer(); // View buffer for type double
		// Count of rateyear written to file
		int rateyearWritten = 0;
		
		while (rateyearWritten < rateyear.length) {
			doubleBuf.put(rateyear, // Array to be written
							rateyearWritten, // Index of 1st element to write
							min(doubleBuf.capacity(), rateyear.length - rateyearWritten));
			buf.limit(8*doubleBuf.position()); // Update byte buffer position
			
			try {
				file.write(buf);
				rateyearWritten += doubleBuf.position();
			} catch (IOException e) {
				e.printStackTrace(System.err);
				System.exit(1);
			}
			doubleBuf.clear();
			buf.clear();
		}
		try {
			outputFile.close(); // Close the file and its channel
		} catch (IOException e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}

	}
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;

import static java.lang.Math.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.DoubleBuffer;

import java.util.Date;

import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.border.Border;



/*
PRG/421 Week 3 Assignment: Mortgage Calculator
 
Author: Jim White
 
Date: May 9, 2011
 
Filename: CalcFrame

This is the mortgage loan program
*/

public class CalcFrame extends JFrame {//Begining

	
	//Sets up the variables for the fields
	
	private JRadioButton planA;
	private JRadioButton planB;
	private JRadioButton planC;
	private JLabel planLabel;
	private JLabel principalLabel;
	private JTextField principalField;
	private JButton calcButton;
	private JButton exitButton;
	private JButton clearButton;
	private JLabel resultLabel;
	private JTextArea resultArea;
	private JTextArea graphArea;
	private ButtonGroup radioGroup;
	private JLabel paymentLabel;
	private JTextField paymentField;
	private JTextField interestField;
	private JLabel interestLabel;
	private JTextField yearsField;
	private JLabel yearsLabel;
	private JLabel graphLabel;
	double years;
	int months = (int)years*12;
	double[] values = new double[months];
	
	private static final int AREA_ROWS = 10;
	private static final int AREA_COLUMNS = 30;
	
	public CalcFrame() {//Creates the frame

			double payment;									//Sets payment variable
			this.setTitle("Mortgage Calculator");		//Sets the name of the window

			
			createTextField();								//Creates text field
			actionButtons();									//Creates buttons
			createPanel();										//Creates panel
			

			//Size and position the window
			Toolkit tk = Toolkit.getDefaultToolkit();	//Gets the toolkit and assigns tk as variable
			Dimension screenSize = tk.getScreenSize();//Gets the screen size
			final int WIDTH = screenSize.width;			//Sets the variable WIDTH to screensize width
			final int HEIGHT = screenSize.height;		//Sets the variable HEIGHT to screensize height
	
			this.setSize(1000, 600);						//Set size
			this.setLocation(WIDTH/14, HEIGHT/26);		//Set position
			
	
	}	
		
	public void createTextField() {							
		
		//Creates Objects
		//Create buttons
		planA = new JRadioButton("7 Years at 5.35%");
		planB = new JRadioButton("15 Years at 5.5%");
		planC = new JRadioButton("30 Years at 5.75%");
		calcButton = new JButton("Calculate");
		exitButton = new JButton("Exit");
		clearButton = new JButton("Clear");

		//Labels
		principalLabel = new JLabel("Amount to be Mortgaged:  ");
		resultLabel = new JLabel("Results: ");
		paymentLabel = new JLabel("The payment would be: ");
		interestLabel = new JLabel("Interest Rate: ");
		yearsLabel = new JLabel("Years to Mortgage: ");
		graphLabel = new JLabel("Graphical View: ");
		
		//Text fields
		final int FIELD_WIDTH = 10;							//field width for text fields
		principalField = new JTextField(FIELD_WIDTH);
		paymentField = new JTextField(FIELD_WIDTH);
		interestField = new JTextField(FIELD_WIDTH);
		yearsField = new JTextField(FIELD_WIDTH);
		paymentField.setForeground(Color.blue);
		paymentField.setEditable(false);
		resultArea = new JTextArea();
		resultArea.setEditable(false);
	
	}
		
	private void createPanel() {		//Adds components to the panel and adds the panel
		//Border
		EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
		BevelBorder bEdge = new BevelBorder(BevelBorder.RAISED);
		//Add elements to the top box
		Box top = Box.createHorizontalBox();
		top.add(Box.createHorizontalStrut(10));
		top.add(Box.createVerticalStrut(25));
		top.add(principalLabel);
		top.add(principalField);
		top.add(Box.createHorizontalStrut(10));
		top.add(interestLabel);
		top.add(interestField);
		top.add(Box.createHorizontalStrut(10));
		top.add(yearsLabel);
		top.add(yearsField);
		top.add(Box.createHorizontalStrut(10));
		top.add(paymentLabel);
		top.add(paymentField);
		top.setBorder(bEdge);
		top.setBackground(Color.BLACK);


		//Add elements to the center box
		Box center = Box.createVerticalBox();
		//center.add(Box.createHorizontalStrut(20));
		center.add(Box.createVerticalStrut(10));
		center.add(resultLabel);
		center.add(Box.createRigidArea(new Dimension(0,5)));
		JScrollPane scrollPane = new JScrollPane(resultArea);
		center.add(scrollPane);
		center.add(Box.createRigidArea(new Dimension(0,5)));
		
		center.add(graphLabel);
		GraphView graph = new GraphView();
		JScrollPane graphPane = new JScrollPane(graph);
		center.add(graphPane);
		graphPane.setBorder(edge);
		center.setBorder(bEdge);
		graph.setValues(values);
		center.setBackground(Color.black);		
		
		//Add elements to the bottom box
		JPanel bottom = new JPanel();
		Dimension bSize = new Dimension(100, 40);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(calcButton);
		calcButton.setBorder(edge);
		calcButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(clearButton);
		clearButton.setBorder(edge);
		clearButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(exitButton);
		exitButton.setBorder(edge);
		exitButton.setPreferredSize(bSize);
		bottom.setBorder(bEdge);
		bottom.setBackground(Color.cyan);
		
		//Add elements to the left box
		Box left = Box.createVerticalBox();
		radioGroup = new ButtonGroup();
		left.add(Box.createVerticalStrut(70));
		left.add(planLabel = new JLabel("Select Option Below:  "));
		left.add(Box.createVerticalStrut(10));
		radioGroup.add(planA);
		left.add(planA);
		radioGroup.add(planB);
		left.add(planB);
		radioGroup.add(planC);
		left.add(planC);
		left.setBorder(bEdge);
		left.setBackground(Color.BLACK);
		
		//Cursors
		Cursor textCur = top.getCursor();
    	Cursor handCur = left.getCursor();
    	top.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    	left.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));


		//Add panels to content pane
		Container content = this.getContentPane();
		content.setLayout(new BorderLayout());
		content.add(center, BorderLayout.CENTER);
		content.add(top, BorderLayout.NORTH);
		content.add(bottom, BorderLayout.SOUTH);
		content.add(left, BorderLayout.WEST);		

	}

	
	private void actionButtons() {									//Create void for actions on elements
	
		class buttonListener implements ActionListener { 	//Add action listener
		
			public void actionPerformed(ActionEvent event) {
				//The following retrieves the rates from the interestrates file
				File aFile = new File("interestRates.txt");
				FileInputStream inFile = null;
				try {													//Try catch for file not found, it must exist
					inFile = new FileInputStream(aFile);
				} catch(FileNotFoundException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				FileChannel inChannel = inFile.getChannel();
				final int RATECOUNT = 6;									//Number of elements to extract from the file
				ByteBuffer buf = ByteBuffer.allocate(8*RATECOUNT);//Sets the buffer up for double
				double[] rates = new double[RATECOUNT];
				try {
					int ratesRead = 0;
					while(inChannel.read(buf) != -1) {
						DoubleBuffer doubleBuf = ((ByteBuffer)(buf.flip())).asDoubleBuffer();//Sets up the buffer
						ratesRead = doubleBuf.remaining();
						doubleBuf.get(rates, 0, doubleBuf.remaining());

						for(int i = 0; i < ratesRead; i++) {	//gets the rates and years

						}
						aFile.deleteOnExit();		//Delets the interestRates text file when the program exits
						buf.clear(); 					// Clear the buffer for the next read
					}
					inFile.close(); 				// Close the file and the channel
					
				} catch(IOException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				//Array for mortgage calculator
				double[][] mortgage = new double [2][3];	//creates two arays with three elements each
				mortgage[0][0] = rates[0];							//Values set to array elements
				mortgage[0][1] = rates[1];							//extracted from the text file
				mortgage[0][2] = rates[2];
				mortgage[1][0] = rates[3];
				mortgage[1][1] = rates[4];
				mortgage[1][2] = rates[5];
				
				
				//Sets command as variable and assigns action
				Object command = event.getSource();
				if (command == calcButton) {

					try {
						Double.parseDouble(interestField.getText());
						Double.parseDouble(yearsField.getText());
			
					}
					catch (Exception e) {
					resultArea.setForeground(Color.red);							//Sets output for exception font color to red
					Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
					resultArea.setFont(eFont);
					resultArea.setText(" "+e.getMessage()+
											" is not a numeric value. \n Please re-enter a numeric value in the field "+
											"\n and try again.");
					return;
					}
					//Sets the variables for the calcButton
					double calcInt = Double.parseDouble(interestField.getText());
					double calcYears = Double.parseDouble(yearsField.getText());
					//Calls the mortgageCalc method and assigns variables
					mortgageCalc (calcInt, calcYears);
					
					
					
				}
				else if(command == exitButton) {
					System.exit(0);
				}
				else if(command == clearButton) {
					principalField.setText("");
					resultArea.setText("");
					paymentField.setText("");
					interestField.setText("");
					yearsField.setText("");
					radioGroup.clearSelection();
				}
				else if(command == planA) {
					mortgageCalc(mortgage[0][0], mortgage[1][0]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planB) {
					mortgageCalc(mortgage[0][1], mortgage[1][1]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planC) {
					mortgageCalc(mortgage[0][2], mortgage[1][2]);//Calls the mortgageCalc method and assigns variables
					
				}				
			}//End action event
		}//End listener

		//Attaches the listeners
		ActionListener listener = new buttonListener();	
		calcButton.addActionListener(listener);								
		exitButton.addActionListener(listener);								
		clearButton.addActionListener(listener);								
		planA.addActionListener(listener);
		planB.addActionListener(listener);
		planC.addActionListener(listener);
	}//End actionButtons

		
	private void mortgageCalc(double interest, double years) {
			
		//Try/catch for input		

			try {
			Double.parseDouble(principalField.getText());
			
			}
			catch (Exception e) {
			resultArea.setForeground(Color.red);							//Sets output for exception font color to red
			Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
			resultArea.setFont(eFont);
			resultArea.setText(" "+e.getMessage()+
									" is not a numeric value. \n Please enter a numeric value in the 'Amount to be Mortgaged:' field "+
									"\n and try again.");
			return;
			}
			double principal = Double.parseDouble(principalField.getText());	//Principal to be mortgaged
			double MI = interest/100/12;													//Sets the interest up for the mortgage formula
			double payment = 0;																//Sets the payment to zero
			double months = years * 12;													//Converts the years to months
			double balance = principal;													//Sets the balance due = principalo
			int paymentNumber = 1;															//Sets initial payment number

	
			//display only two decimal places and a comma seperator
			java.text.DecimalFormat dec = new java.text.DecimalFormat("$###,##0.00"); 	//Set the decimal format
			
			//Mortgage payment formula 
			//P = L[c(1 + c)n]/[(1 + c)n - 1]				
			payment = ((principal*MI)/(1-((pow(1 + MI, -months)))));		
		
			//This outputs the principal, years of payments, interest rate, and the payment
			paymentField.setText(" "+dec.format(payment));
			
			//Headers for columns
			String header =	"\n\n\n\tPayment \tMonthly \tPrincipal \tInterest \tLoan\n "+
									  			"\tNumber\tPayment \tPaid \tPaid \tBalance\n "+
												"\t---------\t----------\t-----------\t---------\t------------\n";
			resultArea.setForeground(Color.black);				//Sets font color to black
			Font font = new Font("Serif", Font.PLAIN, 14);	//Sets the font for the result area
			resultArea.setFont(font);
			resultArea.append(header);						//Prints header
			//Begins the while loop for the payments
				while (paymentNumber <= months){
					
					//Loan balance after n payments have been made and sets the variables
					double monthlyIP=(balance*MI);
					double monthlyPP=(payment-monthlyIP);
					balance = balance-monthlyPP;
					
					//Prints the payment #, payment, interest paid, principal paid, and balance
					resultArea.append("\t"+(int)paymentNumber+"\t" + dec.format(payment)+"\t "+dec.format(monthlyIP)+"\t "
					+dec.format(monthlyPP)+ "\t" +dec.format(balance)+"\n");
					paymentNumber++;
					
			}// end while
	}//End Mortgage calc
}//End



import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;


/**
 * Sample program to show off the GraphCanvas
 */
public class GraphView extends JPanel
{
	GraphCanvas graph = new GraphCanvas();

	public GraphView()
	{
		setLayout(new BorderLayout());
		setSize(200, 200);

		add(graph, BorderLayout.CENTER);
	}

	public void setValues(double[] values) {
		graph.setValues(values);		
	}
	public class CoordCanvas extends Canvas
	{
		protected double viewLeft;
		protected double viewRight;
		protected double viewTop;
		protected double viewBottom;

		public void setXRange(double left, double right)
		{
			viewLeft = left;
			viewRight = right;
		}

		public void setYRange(double top, double bottom)
		{
			viewTop = top;
			viewBottom = bottom;
		}

		public double toX(double x)
		{
			return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
		}

		public double toY(double y)
		{
			return (y - viewTop) * getSize().height / (viewBottom - viewTop);
		}

		public double toWidth(double w)
		{
			return w * getSize().width / Math.abs(viewRight - viewLeft);
		}

		public double toHeight(double h)
		{
			return h * getSize().height / Math.abs(viewBottom - viewTop);
		}
	}


	/** Sample CoordCanvas subclass to draw a bar graph
	 */
	 class GraphCanvas extends CoordCanvas
	 {
		private double[] vals = null;

		public void setValues(double[] vals)
		{
			this.vals = vals;
			repaint();
		}

		public void paint(Graphics comp)
		{
			if (vals == null || vals.length < 1)
				return;

			// find maximum value
			double max = vals[0];
			for (int i = 0; i < vals.length; i++)
				if (vals[i] > max)
					max = vals[i];

			// set coordinate ranges
			this.setXRange(0F, (double)vals.length);
			this.setYRange((double)max, 0F);

			// draw the graph
			Graphics2D comp2D = (Graphics2D)comp;
			for (int i = 0; i < vals.length; i++)
			{
				Rectangle2D.Double remainingPrincipal = new Rectangle2D.Double(toX((double)i),
						toY((double)vals[i]), toWidth(1F), toHeight((double)vals[i]));
				comp2D.fill(remainingPrincipal);
			}
		}
	 }
}





This it what I have.

Is This A Good Question/Topic? 0
  • +

Replies To: I cannot get my graph to show up

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8316
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I cannot get my graph to show up

Posted 19 May 2011 - 03:31 AM

you call

public void setValues(double[] values) {

only once at the beginning but not when you recalculate the payments
Was This Post Helpful? 1
  • +
  • -

#3 aprsr1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 20-February 10

Re: I cannot get my graph to show up

Posted 19 May 2011 - 11:20 AM

pbl, thanks here are the changes I made, but it still doesn't work. The graph will not show up. Do I have to change my layout to a grid layout?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;

import static java.lang.Math.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.DoubleBuffer;

import java.util.Date;

import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.border.Border;



/*
PRG/421 Week 5 Assignment: Mortgage Calculator
 
Author: Jim White
 
Date: May 19, 2011
 
Filename: CalcFrame

This is the mortgage loan program
*/

public class CalcFrame extends JFrame {//Begining

	
	//Sets up the variables for the fields
	
	private JRadioButton planA;
	private JRadioButton planB;
	private JRadioButton planC;
	private JLabel planLabel;
	private JLabel principalLabel;
	private JTextField principalField;
	private JButton calcButton;
	private JButton exitButton;
	private JButton clearButton;
	private JLabel resultLabel;
	private JTextArea resultArea;
	private JTextArea graphArea;
	private ButtonGroup radioGroup;
	private JLabel paymentLabel;
	private JTextField paymentField;
	private JTextField interestField;
	private JLabel interestLabel;
	private JTextField yearsField;
	private JLabel yearsLabel;
	private JLabel graphLabel;
	double years;
	int months = (int)years*12;
	double[] values = new double[months];
	GraphView graph = new GraphView();
	
	private static final int AREA_ROWS = 10;
	private static final int AREA_COLUMNS = 30;
	
	public CalcFrame() {//Creates the frame

			double payment;									//Sets payment variable
			this.setTitle("Mortgage Calculator");		//Sets the name of the window

			
			createTextField();								//Creates text field
			actionButtons();									//Creates buttons
			createPanel();										//Creates panel
			

			//Size and position the window
			Toolkit tk = Toolkit.getDefaultToolkit();	//Gets the toolkit and assigns tk as variable
			Dimension screenSize = tk.getScreenSize();//Gets the screen size
			final int WIDTH = screenSize.width;			//Sets the variable WIDTH to screensize width
			final int HEIGHT = screenSize.height;		//Sets the variable HEIGHT to screensize height
	
			this.setSize(1000, 600);						//Set size
			this.setLocation(WIDTH/14, HEIGHT/26);		//Set position
			
	
	}	
		
	public void createTextField() {							
		
		//Creates Objects
		//Create buttons
		planA = new JRadioButton("7 Years at 5.35%");
		planB = new JRadioButton("15 Years at 5.5%");
		planC = new JRadioButton("30 Years at 5.75%");
		calcButton = new JButton("Calculate");
		exitButton = new JButton("Exit");
		clearButton = new JButton("Clear");

		//Labels
		principalLabel = new JLabel("Amount to be Mortgaged:  ");
		resultLabel = new JLabel("Results: ");
		paymentLabel = new JLabel("The payment would be: ");
		interestLabel = new JLabel("Interest Rate: ");
		yearsLabel = new JLabel("Years to Mortgage: ");
		graphLabel = new JLabel("Graphical View: ");
		
		//Text fields
		final int FIELD_WIDTH = 10;							//field width for text fields
		principalField = new JTextField(FIELD_WIDTH);
		paymentField = new JTextField(FIELD_WIDTH);
		interestField = new JTextField(FIELD_WIDTH);
		yearsField = new JTextField(FIELD_WIDTH);
		paymentField.setForeground(Color.blue);
		paymentField.setEditable(false);
		resultArea = new JTextArea();
		resultArea.setEditable(false);
	
	}
		
	private void createPanel() {		//Adds components to the panel and adds the panel
		//Border
		EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
		BevelBorder bEdge = new BevelBorder(BevelBorder.RAISED);
		//Add elements to the top box
		Box top = Box.createHorizontalBox();
		top.add(Box.createHorizontalStrut(10));
		top.add(Box.createVerticalStrut(25));
		top.add(principalLabel);
		top.add(principalField);
		top.add(Box.createHorizontalStrut(10));
		top.add(interestLabel);
		top.add(interestField);
		top.add(Box.createHorizontalStrut(10));
		top.add(yearsLabel);
		top.add(yearsField);
		top.add(Box.createHorizontalStrut(10));
		top.add(paymentLabel);
		top.add(paymentField);
		top.setBorder(bEdge);
		top.setBackground(Color.BLACK);


		//Add elements to the center box
		Box center = Box.createVerticalBox();
		center.add(Box.createVerticalStrut(10));
		center.add(resultLabel);
		center.add(Box.createRigidArea(new Dimension(0,5)));
		JScrollPane scrollPane = new JScrollPane(resultArea);
		center.add(scrollPane);
		center.add(Box.createRigidArea(new Dimension(0,5)));
		
		center.add(graphLabel);
		GraphView graph = new GraphView();
		JScrollPane graphPane = new JScrollPane(graph);
		center.add(graphPane);
		graphPane.setBorder(edge);
		center.setBorder(bEdge);
		center.setBackground(Color.black);		
		
		//Add elements to the bottom box
		JPanel bottom = new JPanel();
		Dimension bSize = new Dimension(100, 40);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(calcButton);
		calcButton.setBorder(edge);
		calcButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(clearButton);
		clearButton.setBorder(edge);
		clearButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(exitButton);
		exitButton.setBorder(edge);
		exitButton.setPreferredSize(bSize);
		bottom.setBorder(bEdge);
		bottom.setBackground(Color.cyan);
		
		//Add elements to the left box
		Box left = Box.createVerticalBox();
		radioGroup = new ButtonGroup();
		left.add(Box.createVerticalStrut(70));
		left.add(planLabel = new JLabel("Select Option Below:  "));
		left.add(Box.createVerticalStrut(10));
		radioGroup.add(planA);
		left.add(planA);
		radioGroup.add(planB);
		left.add(planB);
		radioGroup.add(planC);
		left.add(planC);
		left.setBorder(bEdge);
		left.setBackground(Color.BLACK);
		
		//Cursors
		Cursor textCur = top.getCursor();
    	Cursor handCur = left.getCursor();
    	top.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    	left.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));


		//Add panels to content pane
		Container content = this.getContentPane();
		content.setLayout(new BorderLayout());
		content.add(center, BorderLayout.CENTER);
		content.add(top, BorderLayout.NORTH);
		content.add(bottom, BorderLayout.SOUTH);
		content.add(left, BorderLayout.WEST);		

	}

	
	private void actionButtons() {									//Create void for actions on elements
	
		class buttonListener implements ActionListener { 	//Add action listener
		
			public void actionPerformed(ActionEvent event) {
				//The following retrieves the rates from the interestrates file
				File aFile = new File("interestRates.txt");
				FileInputStream inFile = null;
				try {													//Try catch for file not found, it must exist
					inFile = new FileInputStream(aFile);
				} catch(FileNotFoundException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				FileChannel inChannel = inFile.getChannel();
				final int RATECOUNT = 6;									//Number of elements to extract from the file
				ByteBuffer buf = ByteBuffer.allocate(8*RATECOUNT);//Sets the buffer up for double
				double[] rates = new double[RATECOUNT];
				try {
					int ratesRead = 0;
					while(inChannel.read(buf) != -1) {
						DoubleBuffer doubleBuf = ((ByteBuffer)(buf.flip())).asDoubleBuffer();//Sets up the buffer
						ratesRead = doubleBuf.remaining();
						doubleBuf.get(rates, 0, doubleBuf.remaining());

						for(int i = 0; i < ratesRead; i++) {	//gets the rates and years

						}
						aFile.deleteOnExit();		//Delets the interestRates text file when the program exits
						buf.clear(); 					// Clear the buffer for the next read
					}
					inFile.close(); 				// Close the file and the channel
					
				} catch(IOException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				//Array for mortgage calculator
				double[][] mortgage = new double [2][3];	//creates two arays with three elements each
				mortgage[0][0] = rates[0];							//Values set to array elements
				mortgage[0][1] = rates[1];							//extracted from the text file
				mortgage[0][2] = rates[2];
				mortgage[1][0] = rates[3];
				mortgage[1][1] = rates[4];
				mortgage[1][2] = rates[5];
				
				
				//Sets command as variable and assigns action
				Object command = event.getSource();
				if (command == calcButton) {

					try {
						Double.parseDouble(interestField.getText());
						Double.parseDouble(yearsField.getText());
			
					}
					catch (Exception e) {
					resultArea.setForeground(Color.red);							//Sets output for exception font color to red
					Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
					resultArea.setFont(eFont);
					resultArea.setText(" "+e.getMessage()+
											" is not a numeric value. \n Please re-enter a numeric value in the field "+
											"\n and try again.");
					return;
					}
					//Sets the variables for the calcButton
					double calcInt = Double.parseDouble(interestField.getText());
					double calcYears = Double.parseDouble(yearsField.getText());
					//Calls the mortgageCalc method and assigns variables
					mortgageCalc (calcInt, calcYears);
					
					
					
				}
				else if(command == exitButton) {
					System.exit(0);
				}
				else if(command == clearButton) {
					principalField.setText("");
					resultArea.setText("");
					paymentField.setText("");
					interestField.setText("");
					yearsField.setText("");
					radioGroup.clearSelection();
				}
				else if(command == planA) {
					mortgageCalc(mortgage[0][0], mortgage[1][0]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planB) {
					mortgageCalc(mortgage[0][1], mortgage[1][1]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planC) {
					mortgageCalc(mortgage[0][2], mortgage[1][2]);//Calls the mortgageCalc method and assigns variables
					
				}				
			}//End action event
		}//End listener

		//Attaches the listeners
		ActionListener listener = new buttonListener();	
		calcButton.addActionListener(listener);								
		exitButton.addActionListener(listener);								
		clearButton.addActionListener(listener);								
		planA.addActionListener(listener);
		planB.addActionListener(listener);
		planC.addActionListener(listener);
	}//End actionButtons

		
	private void mortgageCalc(double interest, double years) {
			
		//Try/catch for input		

			try {
			Double.parseDouble(principalField.getText());
			
			}
			catch (Exception e) {
			resultArea.setForeground(Color.red);							//Sets output for exception font color to red
			Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
			resultArea.setFont(eFont);
			resultArea.setText(" "+e.getMessage()+
									" is not a numeric value. \n Please enter a numeric value in the 'Amount to be Mortgaged:' field "+
									"\n and try again.");
			return;
			}
			double principal = Double.parseDouble(principalField.getText());	//Principal to be mortgaged
			double MI = interest/100/12;													//Sets the interest up for the mortgage formula
			double payment = 0;																//Sets the payment to zero
			int months = (int)years * 12;													//Converts the years to months
			double balance = principal;													//Sets the balance due = principalo
			int paymentNumber = 1;															//Sets initial payment number

	
			//display only two decimal places and a comma seperator
			java.text.DecimalFormat dec = new java.text.DecimalFormat("$###,##0.00"); 	//Set the decimal format
			
			//Mortgage payment formula 
			//P = L[c(1 + c)n]/[(1 + c)n - 1]				
			payment = ((principal*MI)/(1-((pow(1 + MI, -months)))));		
		
			//This outputs the principal, years of payments, interest rate, and the payment
			paymentField.setText(" "+dec.format(payment));
			
			//Headers for columns
			String header =	"\n\n\n\tPayment \tMonthly \tPrincipal \tInterest \tLoan\n "+
									  			"\tNumber\tPayment \tPaid \tPaid \tBalance\n "+
												"\t---------\t----------\t-----------\t---------\t------------\n";
			resultArea.setForeground(Color.black);				//Sets font color to black
			Font font = new Font("Serif", Font.PLAIN, 14);	//Sets the font for the result area
			resultArea.setFont(font);
			resultArea.append(header);						//Prints header
			//Begins the while loop for the payments
				while (paymentNumber <= months){
					
					//Loan balance after n payments have been made and sets the variables
					double monthlyIP=(balance*MI);
					double monthlyPP=(payment-monthlyIP);
					balance = balance-monthlyPP;
					
					//Prints the payment #, payment, interest paid, principal paid, and balance
					resultArea.append("\t"+(int)paymentNumber+"\t" + dec.format(payment)+"\t "+dec.format(monthlyIP)+"\t "
					+dec.format(monthlyPP)+ "\t" +dec.format(balance)+"\n");
					paymentNumber++;
					double[] values = new double[months];
					graph.setValues(values);
			}// end while
			
	}//End Mortgage calc
}//End


Was This Post Helpful? 0
  • +
  • -

#4 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 561
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: I cannot get my graph to show up

Posted 19 May 2011 - 12:40 PM

I think your issue may be in your GraphView class. Five minutes isnt enough to go through all this code, could only scan it. What you want to do when dealing with something larger like this is to debug things, and test them out as individual components. So, for now, go into your GraphView class and create a main method. Create a JFrame, add the GraphView panel to it, set it visible, set its size etc etc. Then call the method that takes the double array and pass it a hardcoded array. The whole point of this exercise is to see if you can get the graph to show up without calling it through other classes. At this moment in time, your adding your graph to your content pane in the other class, and we dont even know if there is anything to display. If your graph doesnt show up when done independently, then we know where the problem is.
Let us know what happens.
Was This Post Helpful? 1
  • +
  • -

#5 aprsr1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 20-February 10

Re: I cannot get my graph to show up

Posted 19 May 2011 - 12:52 PM

Thanks nick I will try that!
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8316
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I cannot get my graph to show up

Posted 19 May 2011 - 03:15 PM

All Java classes should have a main() method for unit testing.
Was This Post Helpful? 0
  • +
  • -

#7 aprsr1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 20-February 10

Re: I cannot get my graph to show up

Posted 19 May 2011 - 06:10 PM

Ok I have made changes to my code and have the following code. The line graph shows up, but so does a copy of my screen. Any suggestions are greatly appreciated!!!

import javax.swing.JFrame;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.channels.FileChannel;

import static java.lang.Math.min;

/*
PRG/421 Week 5 Assignment: Mortgage Calculator
 
Author: Jim White
 
Date: May 19, 2011
 
Filename: CalcViewer

This is the mortgage loan program
*/

public class CalcViewer {

	public static void main(String[] args) {
	
		JFrame frame = new CalcFrame();								//Calls the CalcFrame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	//Sets the close operation
		//frame.pack();
		frame.setVisible(true);											//Sets the window to visible
		
		/*The following creates a text file that contains the interest rate and years
		I thought it would be best create the file and close the channel before the 
		program actually started*/

		double[] rateyear = new double[6]; // Array to store rateyear
		rateyear[0] = 5.35; // Seed the first prime
		rateyear[1] = 5.5; // and the second
		rateyear[2] = 5.75;
		rateyear[3] = 7;
		rateyear[4] = 15;
		rateyear[5] = 30;

		File aFile = new File("interestRates.txt");
		FileOutputStream outputFile = null;
		try {
			outputFile = new FileOutputStream(aFile); // Create the file stream
		} catch (FileNotFoundException e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}
		FileChannel file = outputFile.getChannel(); // Get the channel from the stream
		final int BUFFERSIZE = (8*rateyear.length); // Byte buffer size
		ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
		DoubleBuffer doubleBuf = buf.asDoubleBuffer(); // View buffer for type double
		// Count of rateyear written to file
		int rateyearWritten = 0;
		
		while (rateyearWritten < rateyear.length) {
			doubleBuf.put(rateyear, // Array to be written
							rateyearWritten, // Index of 1st element to write
							min(doubleBuf.capacity(), rateyear.length - rateyearWritten));
			buf.limit(8*doubleBuf.position()); // Update byte buffer position
			
			try {
				file.write(buf);
				rateyearWritten += doubleBuf.position();
			} catch (IOException e) {
				e.printStackTrace(System.err);
				System.exit(1);
			}
			doubleBuf.clear();
			buf.clear();
		}
		try {
			outputFile.close(); // Close the file and its channel
		} catch (IOException e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}

	}
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;

import static java.lang.Math.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.DoubleBuffer;

import java.util.Date;

import java.text.DecimalFormat;

import javax.swing.JComponent;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.border.Border;



/*
PRG/421 Week 5 Assignment: Mortgage Calculator
 
Author: Jim White
 
Date: May 19, 2011
 
Filename: CalcFrame

This is the mortgage loan program
*/

public class CalcFrame extends JFrame {//Begining

	
	//Sets up the variables for the fields
	
	private JRadioButton planA;
	private JRadioButton planB;
	private JRadioButton planC;
	private JLabel planLabel;
	private JLabel principalLabel;
	private JTextField principalField;
	private JButton calcButton;
	private JButton exitButton;
	private JButton clearButton;
	private JLabel resultLabel;
	private JTextArea resultArea;
	private JTextArea graphArea;
	private ButtonGroup radioGroup;
	private JLabel paymentLabel;
	private JTextField paymentField;
	private JTextField interestField;
	private JLabel interestLabel;
	private JTextField yearsField;
	private JLabel yearsLabel;
	private JLabel graphLabel;
	private GraphView graph = new GraphView();
	private static final int AREA_ROWS = 10;
	private static final int AREA_COLUMNS = 30;
	
	public CalcFrame() {//Creates the frame

			double payment;									//Sets payment variable
			this.setTitle("Mortgage Calculator");		//Sets the name of the window

			
			createTextField();								//Creates text field
			actionButtons();									//Creates buttons
			createPanel();										//Creates panel
			

			//Size and position the window
			Toolkit tk = Toolkit.getDefaultToolkit();	//Gets the toolkit and assigns tk as variable
			Dimension screenSize = tk.getScreenSize();//Gets the screen size
			final int WIDTH = screenSize.width;			//Sets the variable WIDTH to screensize width
			final int HEIGHT = screenSize.height;		//Sets the variable HEIGHT to screensize height
	
			this.setSize(1000, 600);						//Set size
			this.setLocation(WIDTH/14, HEIGHT/26);		//Set position
			
	
	}	
		
	public void createTextField() {							
		
		//Creates Objects
		//Create buttons
		planA = new JRadioButton("7 Years at 5.35%");
		planB = new JRadioButton("15 Years at 5.5%");
		planC = new JRadioButton("30 Years at 5.75%");
		calcButton = new JButton("Calculate");
		exitButton = new JButton("Exit");
		clearButton = new JButton("Clear");

		//Labels
		principalLabel = new JLabel("Amount to be Mortgaged:  ");
		resultLabel = new JLabel("Results: ");
		paymentLabel = new JLabel("The payment would be: ");
		interestLabel = new JLabel("Interest Rate: ");
		yearsLabel = new JLabel("Years to Mortgage: ");
		graphLabel = new JLabel("Graphical View: ");
		
		//Text fields
		final int FIELD_WIDTH = 10;							//field width for text fields
		principalField = new JTextField(FIELD_WIDTH);
		paymentField = new JTextField(FIELD_WIDTH);
		interestField = new JTextField(FIELD_WIDTH);
		yearsField = new JTextField(FIELD_WIDTH);
		paymentField.setForeground(Color.blue);
		paymentField.setEditable(false);
		resultArea = new JTextArea();
		resultArea.setEditable(false);
		GraphView graph = new GraphView();
	}
		
	private void createPanel() {		//Adds components to the panel and adds the panel
		//Border
		EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
		BevelBorder bEdge = new BevelBorder(BevelBorder.RAISED);
		//Add elements to the top box
		Box top = Box.createHorizontalBox();
		top.add(Box.createHorizontalStrut(10));
		top.add(Box.createVerticalStrut(25));
		top.add(principalLabel);
		top.add(principalField);
		top.add(Box.createHorizontalStrut(10));
		top.add(interestLabel);
		top.add(interestField);
		top.add(Box.createHorizontalStrut(10));
		top.add(yearsLabel);
		top.add(yearsField);
		top.add(Box.createHorizontalStrut(10));
		top.add(paymentLabel);
		top.add(paymentField);
		top.setBorder(bEdge);
		top.setBackground(Color.BLACK);


		//Add elements to the center box
		Box center = Box.createVerticalBox();
		//center.add(Box.createVerticalStrut(10));
		center.add(resultLabel);
		//center.add(Box.createRigidArea(new Dimension(0,5)));
		JScrollPane scrollPane = new JScrollPane(resultArea);
		center.add(scrollPane);
		center.add(Box.createRigidArea(new Dimension(0,5)));
		
		center.add(graphLabel);
		//JScrollPane graphPane = new JScrollPane(graph);
		this.graph = graph;
		center.add(graph);
		graph.setBorder(edge);
		center.setBorder(bEdge);
		center.setBackground(Color.black);		
		
		//Add elements to the bottom box
		JPanel bottom = new JPanel();
		Dimension bSize = new Dimension(100, 40);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(calcButton);
		calcButton.setBorder(edge);
		calcButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(clearButton);
		clearButton.setBorder(edge);
		clearButton.setPreferredSize(bSize);
		bottom.add(Box.createHorizontalStrut(20));
		bottom.add(exitButton);
		exitButton.setBorder(edge);
		exitButton.setPreferredSize(bSize);
		bottom.setBorder(bEdge);
		bottom.setBackground(Color.cyan);
		
		//Add elements to the left box
		Box left = Box.createVerticalBox();
		radioGroup = new ButtonGroup();
		left.add(Box.createVerticalStrut(70));
		left.add(planLabel = new JLabel("Select Option Below:  "));
		left.add(Box.createVerticalStrut(10));
		radioGroup.add(planA);
		left.add(planA);
		radioGroup.add(planB);
		left.add(planB);
		radioGroup.add(planC);
		left.add(planC);
		left.setBorder(bEdge);
		left.setBackground(Color.BLACK);
		
		//Cursors
		Cursor textCur = top.getCursor();
    	Cursor handCur = left.getCursor();
    	top.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    	left.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));


		//Add panels to content pane
		Container content = this.getContentPane();
		content.setLayout(new BorderLayout());
		content.add(center, BorderLayout.CENTER);
		content.add(top, BorderLayout.NORTH);
		content.add(bottom, BorderLayout.SOUTH);
		content.add(left, BorderLayout.WEST);		

	}

	
	private void actionButtons() {									//Create void for actions on elements
	
		class buttonListener implements ActionListener { 	//Add action listener
		
			public void actionPerformed(ActionEvent event) {
				//The following retrieves the rates from the interestrates file
				File aFile = new File("interestRates.txt");
				FileInputStream inFile = null;
				try {													//Try catch for file not found, it must exist
					inFile = new FileInputStream(aFile);
				} catch(FileNotFoundException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				FileChannel inChannel = inFile.getChannel();
				final int RATECOUNT = 6;									//Number of elements to extract from the file
				ByteBuffer buf = ByteBuffer.allocate(8*RATECOUNT);//Sets the buffer up for double
				double[] rates = new double[RATECOUNT];
				try {
					int ratesRead = 0;
					while(inChannel.read(buf) != -1) {
						DoubleBuffer doubleBuf = ((ByteBuffer)(buf.flip())).asDoubleBuffer();//Sets up the buffer
						ratesRead = doubleBuf.remaining();
						doubleBuf.get(rates, 0, doubleBuf.remaining());

						for(int i = 0; i < ratesRead; i++) {	//gets the rates and years

						}
						aFile.deleteOnExit();		//Delets the interestRates text file when the program exits
						buf.clear(); 					// Clear the buffer for the next read
					}
					inFile.close(); 				// Close the file and the channel
					
				} catch(IOException e) {
					e.printStackTrace(System.err);
					System.exit(1);
				}
				//Array for mortgage calculator
				double[][] mortgage = new double [2][3];	//creates two arays with three elements each
				mortgage[0][0] = rates[0];							//Values set to array elements
				mortgage[0][1] = rates[1];							//extracted from the text file
				mortgage[0][2] = rates[2];
				mortgage[1][0] = rates[3];
				mortgage[1][1] = rates[4];
				mortgage[1][2] = rates[5];
				
				
				//Sets command as variable and assigns action
				Object command = event.getSource();
				if (command == calcButton) {

					try {
						Double.parseDouble(interestField.getText());
						Double.parseDouble(yearsField.getText());
			
					}
					catch (Exception e) {
					resultArea.setForeground(Color.red);							//Sets output for exception font color to red
					Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
					resultArea.setFont(eFont);
					resultArea.setText(" "+e.getMessage()+
											" is not a numeric value. \n Please re-enter a numeric value in the field "+
											"\n and try again.");
					return;
					}
					//Sets the variables for the calcButton
					double calcInt = Double.parseDouble(interestField.getText());
					double calcYears = Double.parseDouble(yearsField.getText());
					//Calls the mortgageCalc method and assigns variables
					mortgageCalc (calcInt, calcYears);
					
					
					
				}
				else if(command == exitButton) {
					System.exit(0);
				}
				else if(command == clearButton) {
					principalField.setText("");
					resultArea.setText("");
					paymentField.setText("");
					interestField.setText("");
					yearsField.setText("");
					radioGroup.clearSelection();
					double x[] = new double[1];
					x[0] = 0;
					graph.setPrincipalValues(x, 0, 0);
				}
				else if(command == planA) {
					mortgageCalc(mortgage[0][0], mortgage[1][0]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planB) {
					mortgageCalc(mortgage[0][1], mortgage[1][1]);//Calls the mortgageCalc method and assigns variables
				}
				else if(command == planC) {
					mortgageCalc(mortgage[0][2], mortgage[1][2]);//Calls the mortgageCalc method and assigns variables
					
				}	
						
			}//End action event
		}//End listener

		//Attaches the listeners
		ActionListener listener = new buttonListener();	
		calcButton.addActionListener(listener);								
		exitButton.addActionListener(listener);								
		clearButton.addActionListener(listener);								
		planA.addActionListener(listener);
		planB.addActionListener(listener);
		planC.addActionListener(listener);
	}//End actionButtons

		
	private void mortgageCalc(double interest, double years) {
			
		//Try/catch for input		

			try {
			Double.parseDouble(principalField.getText());
			
			}
			catch (Exception e) {
			resultArea.setForeground(Color.red);							//Sets output for exception font color to red
			Font eFont = new Font("Times New Roman", Font.BOLD, 24);	//Sets the font for the exception message
			resultArea.setFont(eFont);
			resultArea.setText(" "+e.getMessage()+
									" is not a numeric value. \n Please enter a numeric value in the 'Amount to be Mortgaged:' field "+
									"\n and try again.");
			return;
			}
			double principal = Double.parseDouble(principalField.getText());	//Principal to be mortgaged
			double MI = interest/100/12;													//Sets the interest up for the mortgage formula
			double payment = 0;																//Sets the payment to zero
			int months = (int)years * 12;													//Converts the years to months
			double balance = principal;													//Sets the balance due = principalo
			int paymentNumber = 1;															//Sets initial payment number
			double[] values = new double[months];
	
			//display only two decimal places and a comma seperator
			java.text.DecimalFormat dec = new java.text.DecimalFormat("$###,##0.00"); 	//Set the decimal format
			
			//Mortgage payment formula 
			//P = L[c(1 + c)n]/[(1 + c)n - 1]				
			payment = ((principal*MI)/(1-((pow(1 + MI, -months)))));		
		
			//This outputs the principal, years of payments, interest rate, and the payment
			paymentField.setText(" "+dec.format(payment));
			
			//Headers for columns
			String header =	"\n\n\n\tPayment \tMonthly \tPrincipal \tInterest \tLoan\n "+
									  			"\tNumber\tPayment \tPaid \tPaid \tBalance\n "+
												"\t---------\t----------\t-----------\t---------\t------------\n";
			resultArea.setForeground(Color.black);				//Sets font color to black
			Font font = new Font("Serif", Font.PLAIN, 14);	//Sets the font for the result area
			resultArea.setFont(font);
			resultArea.append(header);						//Prints header
			
			//Begins the while loop for the payments
				while (paymentNumber <= months){
					
					//Loan balance after n payments have been made and sets the variables
					double monthlyIP=(balance*MI);
					double monthlyPP=(payment-monthlyIP);
					balance = balance-monthlyPP;
					
					//Prints the payment #, payment, interest paid, principal paid, and balance
					resultArea.append("\t"+(int)paymentNumber+"\t" + dec.format(payment)+"\t "+dec.format(monthlyIP)+"\t "
					+dec.format(monthlyPP)+ "\t" +dec.format(balance)+"\n");
					paymentNumber++;
					graph.setPrincipalValues(values, balance, payment);
					
						
					
					
			}// end while

			
	}//End Mortgage calc
}//End



import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class GraphView extends JPanel {

		private double[] months = null;
		private double balance;
		private double payment;


	public void setPrincipalValues(double[] months, double balance, double payment){
	
			this.months = months;
			this.balance = balance;
			this.payment = payment;
			repaint();
	}

		public void paint(Graphics g) {
		
	
			if (months == null || months.length < 1)
					return;

			
			//Comment
			Graphics2D g2D = (Graphics2D)g;
			
			g2D.setPaint(Color.RED);								//Draw in red
			
			for (int i = 0; i < months.length; i++) {
			
				double payments = (payment*months.length);
				
				Point2D.Double p1 = new Point2D.Double(months[i], payments/1000);
				Point2D.Double p2 = new Point2D.Double(months.length, balance/1000);
				Line2D.Double line = new Line2D.Double(p1, p2);
				g2D.draw(line);
				g2D.drawString("Amount Owed", 60, 100);

				
			}
		}
	}


Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8316
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I cannot get my graph to show up

Posted 20 May 2011 - 03:06 AM

Kids never listen :(
This is exactly what nick2price asked you to do... and I strongly second his suggestion

Now you can check that your GraphView class works :^:

Now if not displayed... it is just because you do not call setValues() :)

import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;


/**
 * Sample program to show off the GraphCanvas
 */
public class GraphView extends JPanel
{
	GraphCanvas graph = new GraphCanvas();

	public GraphView()
	{
		setLayout(new BorderLayout());
		setSize(200, 200);

		add(graph, BorderLayout.CENTER);
	}

	public void setValues(double[] values) {
		graph.setValues(values);		
	}
	
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		GraphView gv = new GraphView();
		frame.add(gv);
		frame.setSize(700,500);
		frame.setVisible(true);
		double[] values = {1.0, 2.9, 3.0, 4.0, 5.0, 6.0};
		gv.setValues(values);	
	}
	public class CoordCanvas extends Canvas
	{
		protected double viewLeft;
		protected double viewRight;
		protected double viewTop;
		protected double viewBottom;

		public void setXRange(double left, double right)
		{
			viewLeft = left;
			viewRight = right;
		}

		public void setYRange(double top, double bottom)
		{
			viewTop = top;
			viewBottom = bottom;
		}

		public double toX(double x)
		{
			return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
		}

		public double toY(double y)
		{
			return (y - viewTop) * getSize().height / (viewBottom - viewTop);
		}

		public double toWidth(double w)
		{
			return w * getSize().width / Math.abs(viewRight - viewLeft);
		}

		public double toHeight(double h)
		{
			return h * getSize().height / Math.abs(viewBottom - viewTop);
		}
	}


	/** Sample CoordCanvas subclass to draw a bar graph
	 */
	 class GraphCanvas extends CoordCanvas
	 {
		private double[] vals = null;

		public void setValues(double[] vals)
		{
			System.out.println("In setValues de GraphCanvas");
			this.vals = vals;
			repaint();
		}

		public void paint(Graphics comp)
		{
			System.out.println("In paint of GraphCanvas");
			if (vals == null || vals.length < 1)
				return;

			// find maximum value
			double max = vals[0];
			for (int i = 0; i < vals.length; i++)
				if (vals[i] > max)
					max = vals[i];

			// set coordinate ranges
			this.setXRange(0F, (double)vals.length);
			this.setYRange((double)max, 0F);

			// draw the graph
			Graphics2D comp2D = (Graphics2D)comp;
			for (int i = 0; i < vals.length; i++)
			{
				Rectangle2D.Double remainingPrincipal = new Rectangle2D.Double(toX((double)i),
						toY((double)vals[i]), toWidth(1F), toHeight((double)vals[i]));
				comp2D.fill(remainingPrincipal);
			}
		}
	 }
}


Was This Post Helpful? 0
  • +
  • -

#9 aprsr1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 20-February 10

Re: I cannot get my graph to show up

Posted 20 May 2011 - 07:28 AM

PBL,

Thanks! I did run it like that and it ran fine, just so you know I did do it. I could not get it to show up still in the graph pane, so I wrote the other code of a simple line graph and it does show up in the graph pane and I did not change any of the code in the CalcFrame, so I know the call is there to the GraphView setValues. I put the code in from the simple line graph
Graphics2D g2D = (Graphics2D)g;
			
			g2D.setPaint(Color.GREEN);
			g2D.drawString("Equity", 600, 200);
			
			
			
			for (int i = 0; i < months.length; i++) {
			
				g2D.setPaint(Color.RED);
				g2D.drawString("Amount Owed", 0, 50);
				double payments = (payment*months.length);
				Point2D.Double p1 = new Point2D.Double(0, 225);
				Point2D.Double p2 = new Point2D.Double(months.length+500, balance/1000);
				Line2D.Double line1 = new Line2D.Double(p1, p2);
				g2D.draw(line1);

				
				g2D.setPaint(Color.BLUE);
				g2D.drawString(months.length/12+" Years", months.length+200, 100);

			}


instead of what was in the original GraphView and it shows up, so I am assuming it must be something in the for loop? I couldn't figure it out, so I moved on to the easier graph to at least get some output. I am still working on the rectangles though, so if you have any further thoughts please share!!! Thanks again for everyone's help!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1