Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Urgent help needed for beginner adding graph to program

Posted on 2009-04-05
14
Medium Priority
?
226 Views
Last Modified: 2013-11-23
Hi - I am desparately trying to incorporate a graph into my program. I am far from done; can't even get a simple line to display in the graph. Since I was having trouble; instructor suggested starting small. If someone can please explain what I am doing wrong and what I need to do, I might start making some progress.

I cannot use a 3rd party graph class

I have included my code and attached my sequential file. Please ignore the areas that are commented out, I was trying to add other stuff and it's just not working :-)

P.S. I have looked at other examples, the one good one was much older and won't help me...I need to get my existing program to show a line in the panel when the graph button is clicked.
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 MortgageWk5New extends JFrame implements ActionListener
{
	  //variables
      double [] rate;
      int[] term;
      double r;
      double t;
      private float[] yearInterest;
      private float[] yearPrinciple;
 
      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");
 
      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 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);
 
           // 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 graphPanel());
		mFrame.setSize(800, 600);
		mFrame.setLocation(200,100);
 
		JMenu menuExit = new JMenu ("Exit", true);
		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));
 
	  			//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 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)
	{
		int x=0, y=0;
	Graphics2D g2 = (Graphics2D)g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	//Create Point2D.Double
	Point2D.Double point = new Point2D.Double(x, y);
 
 
 
}
 
}

Open in new window

data.txt
0
Comment
Question by:zad1999
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 3
14 Comments
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24072058
You'd gotten your curly braces a bit muddled at the end of the file, which was somewhat disguised by the <not too great> code layout. I've corrected that, and formatted your code. See attached.

Advice: use GridBagLayout for your component layout.
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 MortgageWk5New extends JFrame implements ActionListener
{
	//variables
	double[]			rate;
	int[]				term;
	double				r;
	double				t;
	private float[]		yearInterest;
	private float[]		yearPrinciple;
	
	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");
	
	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 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);
		
		// 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 graphPanel());
			mFrame.setSize(800, 600);
			mFrame.setLocation(200, 100);
			
			JMenu menuExit = new JMenu("Exit", true);
			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));
			
			//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 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)
		{
			int x = 0, y = 0;
			Graphics2D g2 = (Graphics2D) g;
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			//Create Point2D.Double
			Point2D.Double point = new Point2D.Double(x, y);
			
			g2.drawLine(10, 10, 500, 500);
			
		}
	}
	
}

Open in new window

0
 

Author Comment

by:zad1999
ID: 24072140
I still don't see a line when the graph button is clicked???? or am I missing something.

Thanks for formatting the code, it is a bit messy, but can you please look and see why a line will not display???
I realize I need something like:
g2.drawLine(10,25, 40, 55);
but when I place that with the code for the graph button, program won't compile. Same goes if I try to call the method in the code for the graph button.  Where do I put code that I want to show up in the window that opens when the graph button is clicked?
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24072164
Did you try my code?

I've added added a g2.drawLine call, which compiles fine, and it runs as expected for me; when I click the Graph button, a window appears with a line on it...
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 12

Expert Comment

by:basav_com
ID: 24072228
Check this code:


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 MortgageWk5New extends JFrame implements ActionListener
{
	  //variables
      double [] rate;
      int[] term;
      double r;
      double t;
      private float[] yearInterest;
      private float[] yearPrinciple;
 
      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");
 
      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 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);
 
           // 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 graphPanel());
		mFrame.setSize(800, 600);
		mFrame.setLocation(200,100);
 
		JMenu menuExit = new JMenu ("Exit", true);
		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));
 
	  			//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 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)
		{
			int x=0, y=0;
		Graphics2D g2 = (Graphics2D)g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		//Create Point2D.Double
		Point2D.Double point1 = new Point2D.Double(x, y);
		Point2D.Double point2 = new Point2D.Double(200,300);
		
		Line2D line1 = new Line2D.Double(point1, point2);
		g2.draw(line1);
 	 
	    }
 
	}
 
 
 
}

Open in new window

0
 
LVL 12

Expert Comment

by:basav_com
ID: 24072233
Hope this is helpful:

public void paint(Graphics g)
            {
                  int x=0, y=0;
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //Create Point2D.Double
            Point2D.Double point1 = new Point2D.Double(x, y);
            Point2D.Double point2 = new Point2D.Double(200,300);
            
            Line2D line1 = new Line2D.Double(point1, point2);
            g2.draw(line1);
        
          }


Check the above working code.

More help here: http://java.comsci.us/examples/awt/geom/Point2D.html
0
 
LVL 12

Expert Comment

by:basav_com
ID: 24072298
One note here, drawLine can take integers only not double values.  Your graph double .. precision values are lost if you use drawLine.

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html

Hence you have to use like this only to preserve the double values precision which you have already computed from your first screen.
public void paint(Graphics g)
            {
                  int x=0, y=0;
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //Create Point2D.Double
            Point2D.Double point1 = new Point2D.Double(x, y);
            Point2D.Double point2 = new Point2D.Double(200,300);
           
            Line2D line1 = new Line2D.Double(point1, point2);
            g2.draw(line1);
       
          }
0
 

Author Comment

by:zad1999
ID: 24072455
InteractiveMind:
I appologize, I swore I replaced your code with mine, but somehow I must have copied my old code by accident. When I did it this time, it worked. Grrrrrrr...

I will study what you have done and what the other person posted and see if I can get any further with incorporating a "real graph" into my program.

Thanks!!
0
 

Author Comment

by:zad1999
ID: 24072481
bassav_com,
The precision is not crucial to this program, just getting a working graph that shows yearly interest/yearly principle. So in this case, do you think it still necessary for me to write my code the way you suggested? I'm trying to take the easiest route possible and even then, am doubtful I will finish b4 assignment is due.

Thanks for taking the time to help me!!
0
 
LVL 12

Accepted Solution

by:
basav_com earned 500 total points
ID: 24072532
I hope you will understand what Iam saying....when you try to incorporate the code and draw the graph with your values.

How will you draw the graph with these values using drawLine() ? ???
Interest                        Principle                       Balance
 $020.88                        $016.34                      $4,538.66

The code that i have posted is very simple.
Just define the starting point(point1) and ending point(point2) and draw the line between these points.


0
 
LVL 25

Assisted Solution

by:InteractiveMind
InteractiveMind earned 500 total points
ID: 24072684
> I will study what you have done
Your problem was that you'd defined paint() *outside* of the graphPanel class, and so it was affecting your main JFrame.
0
 

Author Comment

by:zad1999
ID: 24072687
Ok - I see your point. I will play with this some more. If I need more help, I will post another question.
0
 

Author Comment

by:zad1999
ID: 24072699
Interactive mind - thanks for the info; I guess that's the only reason my line was not displaying; the code is getting long which causes confusion for a beginner. Thanks again!!
0
 

Author Closing Comment

by:zad1999
ID: 31566765
Thanks again for the help; it's amazing how something simple can be so confusing
0
 
LVL 12

Expert Comment

by:basav_com
ID: 24072720
I guess that's the only reason my line was not displaying  ----> That's not the only reason, along with that... you have neither used drawLine or draw methods to actually draw the line ;)
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question