Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By Fubarable

Thread: Help with graphs

  1. #1
    thelgar is offline DeathBringer
    Join Date
    Jan 2012
    Location
    California
    Posts
    4
    Rep Power
    0

    Default Help with graphs

    ok i am working on my final and have hit a dead end. I am not sure i am in the right area for this but i need help.

    my code i have thus far is not showing me a graph. this project is due in 2 days and i am far from ready. The graph needs to grab the "Principal Paid" and graph its progress through the full length of the loan.

    here is what i have, could really use some help completing it.

    Java Code:
    package mortgagecalc;
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Rectangle2D;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    
    
    public class MortgageCalc extends JFrame {
            
            final ArrayList<Double> rateList = new ArrayList<Double>();
            final ArrayList<Integer> yearList = new ArrayList<Integer>();
    	//String mortgage[] = { "Select Mortgage" };
    	//String[] toReplace;
    	DecimalFormat money = new DecimalFormat("$###,###,###.00");
    
    	// Define the JPanel where we will draw and place all of our components.
    	JPanel contentPanel = null;
    
    	// GUI elements to display labels, fields, table, scroll pane for current
    	// information
    	JLabel mainTitle = null;
    	JLabel principalLabel = null;
    	JTextField principalText = null;
    	JLabel yearsLabel = null;
    	JTextField yearsText = null;
    	JLabel rateLabel = null;
    	JTextField rateText = null;
    	JLabel chooseLabel = null;
    	JComboBox chooseCombo = null;
    	JRadioButton selectionOne = null;
    	JRadioButton selectionTwo = null;
    	ButtonGroup buttongroup = null;
    
    	// GUI text area for results with scroll pane
    	JTextArea result = null;
            JTextArea GraphArea = new JTextArea(19,50);
    	JScrollPane scrollingResults = null;
    
    	// GUI for Table with scroll pane
    	MyJTable totalAmounts = null;
            JScrollPane scrollingTable = null;
            MyDTableModel model;
    
    	// Creates button for graphing
    	JButton graphButton = null;
    
            // Creates the button for calculation of the mortgage payments
    	JButton calculateButton = null;
    
    	// Creates a button for reset button
    	JButton resetButton = null;
    	
    	// Declaration of variables
            int numberOfLinesGenerated=1;
            double numberYears; //term mortgage
            double principal; // amount borrowed
            double rate;  // interest for mortgage
            double monthlyPayment;  // monthly payment for mortgage
            double monthlyRate ; // monthly interest
            double totalMonths; // number of months for mortgage payments
            double interestPaid; //interest amount added for each month
            double principalPaid;
    
    	// This is the class constructor - initialize the components
    
    	public MortgageCalc() {
    		super();
    		initialize();
    	}
    
    	// Window size, JPanel, setTitle
    	public void initialize() {
    		this.setSize(720, 670);
    		this.setContentPane(getJPanel());
    		this.setTitle("Mortgage Calculator by Luther Mann");
    	}
    
    	public JPanel getJPanel() {
    		if (contentPanel == null) {
                        readFile();
    			contentPanel = new JPanel();
    			contentPanel.setLayout(null);
    			contentPanel.setBackground(Color.LIGHT_GRAY);
    
    			// GUI elements to display labels and fields for current information
    			// to include Alignment, Boundary, Title, Font, Font Size, Color
    
    			// Main Title of the Calculator
    			mainTitle = new JLabel();
    			mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
    			mainTitle.setBounds(130, 20, 400, 30);
    			mainTitle.setText("Luther's Loan Calculator");
    			mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
    			mainTitle.setForeground(Color.blue);
    			contentPanel.add(mainTitle);
                            
                            //Selection button 1
                            selectionOne = new JRadioButton();
                            selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
                            selectionOne.setBounds(125, 65, 160, 15);
                            selectionOne.setText("Preset Loan Terms");
                            selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
                            selectionOne.setForeground(Color.black);
                            selectionOne.setSelected(true);
                            contentPanel.add(selectionOne);
                    
                            //Selection Button 2
                            selectionTwo = new JRadioButton();
                            selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
                            selectionTwo.setBounds(350, 65, 180, 15);
                            selectionTwo.setText("Enter Your Loan Terms");
                            selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
                            selectionTwo.setForeground(Color.black);
                            contentPanel.add(selectionTwo);
    
    			// Principal Label
    			principalLabel = new JLabel();
    			principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    			principalLabel.setBounds(120, 65, 200, 75);
    			principalLabel.setText("Mortgage Principle Amount : ");
    			principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
    			principalLabel.setForeground(Color.blue);
    			contentPanel.add(principalLabel);
    
    			// Principal Text Field Features
    			principalText = new JTextField();
    			principalText.setBounds(350, 90, 160, 25);
    			contentPanel.add(principalText);
    
    			// Mortgage Plan Label
    			chooseLabel = new JLabel();
    			chooseLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    			chooseLabel.setBounds(90, 125, 220, 25);
    			chooseLabel.setText("Select Mortgage Plan : ");
    			chooseLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
    			chooseLabel.setForeground(Color.blue);
    			contentPanel.add(chooseLabel);
    
    			
                            
                            // String for Mortgage Variation
    			String mortgage[] = new String[yearList.size() + 1];
                            
                            mortgage[0] = "Select Mortgage";
                            
                            for (int i = 0; i < rateList.size(); i++)
                            {
                            mortgage[i + 1] = yearList.get(i) + " years " + rateList.get(i) +"%";
                    }
                                                    
    			chooseCombo = new JComboBox(mortgage);
    			chooseCombo.setBounds(350, 125, 180, 30);
    			chooseCombo.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent event) {
    					setMortgage();
    				}
    			});
    			contentPanel.add(chooseCombo);
    			
    			
    			// Text Area for result
    			result = new JTextArea(5, 20);
                            result.setEditable(false);
    			result.setBounds(170, 250, 350, 75);
    			scrollingResults = new JScrollPane(result);
    			contentPanel.add(result);
    			
    			//Table for amortization calculations
    			totalAmounts = new MyJTable();
    			scrollingTable = new JScrollPane (totalAmounts);
    			scrollingTable.setBounds(25, 425, 600, 175);
    			contentPanel.add(scrollingTable);
    
    			// Number of Years Label
    			yearsLabel = new JLabel();
    			yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    			yearsLabel.setBounds(90, 200, 220, 25);
    			yearsLabel.setText("Mortgage Term : ");
    			yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
    			yearsLabel.setForeground(Color.blue);
                            //yearsLabel.setVisible(false);
    			contentPanel.add(yearsLabel);
    
    			// Number of Years Text Field
    			yearsText = new JTextField();
    			yearsText.setBounds(350, 205, 160, 25);
                            //yearsText.setVisible(false);
                            yearsText.setEditable(false);
    			contentPanel.add(yearsText);
    
    			// Annual Interest Rate Label
    			rateLabel = new JLabel();
    			rateLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    			rateLabel.setBounds(90, 165, 220, 25);
    			rateLabel.setText("Annual Interest Rate(Decimal) : ");
    			rateLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
    			rateLabel.setForeground(Color.blue);
                            //rateLabel.setVisible(false);
    			contentPanel.add(rateLabel);
    
    			// Annual Interest Rate Text Field
    			rateText = new JTextField();
    			rateText.setBounds(350, 165, 160, 25);
                            rateText.setEditable(false);
                            //rateText.setVisible(false);
    			contentPanel.add(rateText);
    
    			// Button for Graphing
    			graphButton = new JButton();
    			graphButton.setBounds(395, 350, 110, 30);
    			graphButton.setText("Graph");
    			contentPanel.add(graphButton);
    
    			// Button for reset button
    			resetButton = new JButton();
    			resetButton.setBounds(285, 350, 110, 30);
    			resetButton.setText("Reset");
    			contentPanel.add(resetButton);
    
    			// Button for calculation of the mortgage payments
    			calculateButton = new JButton();
    			calculateButton.setBounds(175, 350, 110, 30);
    			calculateButton.setText("Calculate");
    			contentPanel.add(calculateButton);
    
    			// ---- Radio Button Listeners
                            selectionOne.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent event) {
    			hideSelectionTwo();
                            }
                            });
                            selectionTwo.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent event) {
    			
                            // ---- display results 
                    	displaySelectionTwo();
    			}
                            });
    
                            
                            // Action listener to the reset button
    
    			resetButton.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					onButtonReset();
    				}
    			});
    			
    			
    			graphButton.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					drawGraph();
    				}
    			});
    			
    
    			calculateButton.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					principal=getDouble(principalText.getText());
    					calculate();
    				{
    			
    			//Gets the values from the combo box or text box
                                        
    	if (selectionOne.isSelected()){
                 int index = (int)chooseCombo.getSelectedIndex();
                    rateList.get(index - 1);
                    yearList.get(index - 1);
                    rate = rateList.get(index - 1);
                    numberYears = yearList.get(index - 1);
                     
                /*if (str.equals("30 years at 5.75%")) {
    	        rate = 0.0575;
    	        numberYears = 30;
    		          }
               else
                   if(str.equals("20 years at 5.65%")) {
                       rate = 0.0565;
                       numberYears = 20;
                   }
               
                else			
                    if(str.equals("10 years at 5%")) {
                        rate = 0.055;
                        numberYears = 10;
                            }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rate = 0.0535;
                    numberYears = 7;
                    }
               
            }*/
            //else {
                
                    rate = Double.parseDouble(rateText.getText());
                    numberYears = Double.parseDouble(yearsText.getText());
                    
                    rate = rate/100;
               
               }
             
                     }                    
    					  
    			 //Calculates the number of months for mortgage
    			 
                        totalMonths = numberYears * 12;
    
              //Caluclates the monthly interest rate
    			 
                        monthlyRate = rate/12.0;
    
              //Calculates the monthly payment for mortgage
    			 
                        monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));
    
    
                       // Sets the result text
    						 
                        result.setText("Loan Amount = " + money.format(principal)
                        +"\nInterest Rate = " + (rate * 100) +"%"+"\nLength of Loan = "
                        + Math.round(numberYears * 12.0) + " months"+"\nMonthly Payment = "
                        + money.format(monthlyPayment)); //calling the monthlyPayment
    
                        // Have the necessary information for the model lets recalculate it.
    						  
                        if(totalAmounts != null){
                            totalAmounts.setModel(getModel());
                        }
    
                    }
                });
                //Adds the calculate button
    				
                contentPanel.add(calculateButton);
    
                //Adds the scroll pane
    				
                contentPanel.add(getScrollPane());
            }
    
            return contentPanel;
        }
            public void readFile()
            {
              String dataFileName = "src/mortgagecalc/loandata.txt";
    
    		//create arrays to hold values in file
    		//final ArrayList<Double> rateList = new ArrayList<Double>();
    		//final ArrayList<Integer> yearList = new ArrayList<Integer>();
    
    		//open and read text file
    		try
    		{
    			BufferedReader br = new BufferedReader(new FileReader(dataFileName));
    			String line;
    
    			while ((line = br.readLine()) != null)
    			{
    				String values[] = line.split(","); //splits each word after comma and stores values in array "values"
    				int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
    				double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line
    
    				yearList.add(value1); //adds all value1 integers to arraylist
    				rateList.add(value2); //adds all value2 doubles to arraylist
    			}
    
    			br.close();
    		}
    
    		catch (FileNotFoundException e)
    		{
    			e.printStackTrace();
    		}
    
    		catch (IOException e)
    		{
    			e.printStackTrace();
    		}  
            }
    			
    //setMortgage Calculation//
    
    	public void setMortgage() {
                
                int index = (int)chooseCombo.getSelectedIndex();
                    try {
                    if (index <= 0 );
                    {
                    
                    }
                    //rateList.get(index);
                    //yearList.get(index);
                        double rateTemp = rateList.get(index - 1);
                        int yearsTemp = yearList.get(index - 1);
                        String rateString = Double.toString(rateTemp);
                        String yearString = Integer.toString(yearsTemp);
                    
                        rateText.setText(rateString);
                        yearsText.setText(yearString);
                
                
    		/*String str = (String) chooseCombo.getSelectedItem();
    
    		if (str.equals("30 years at 5.75%")) {
    			rateText.setText("0.0575");
    			yearsText.setText("30");
    			}
                    else			
                        if(str.equals("20 years at 5.65%")) {
                        rateText.setText("0.0565");
                        yearsText.setText("20");
                        }
    		else			
                        if(str.equals("10 years at 5%")) {
                        rateText.setText("0.05");
                        yearsText.setText("10");
                        }
                    else
                        if(str.equals("7 years at 5.35%")) {
                        rateText.setText("0.0535");
                        yearsText.setText("7");	
    		}*/
                }catch (java.lang.ArrayIndexOutOfBoundsException e){
                    
                }
                    
                }
                   
            
    
    	
    // Information for Reset Button//
    	
    	public void onButtonReset() {
    		principalText.setText("");
    		rateText.setText("");
    		yearsText.setText("");
                    result.setText("");
                    model.setRowCount(0);
    	}
    
    // Calculate() call//
    	
    	public void calculate() {	
    		double principal = getDouble(principalText.getText());
    		int number_of_years = Integer.parseInt(yearsText.getText());
    		double interest_rate = getDouble(rateText.getText());
            if(interest_rate > 1.0)interest_rate = interest_rate/100.0;
    
    		// Calculates the number of months for mortgage so as to determine the number of payments to be made
    					
    					int number_of_months = number_of_years * 12;
    
    		// Calulates the monthly interest rate
    		
    					double monthly_interest_rate = interest_rate / 12.0;
    
    		// Equation that calculates the monthly payment for mortgage
    		
    					double monthly_payment = (principal * monthly_interest_rate)/ (1 - Math.pow(1 + monthly_interest_rate, -number_of_months));
    
    		// Sets the result text
    		result.setText("Loan Amount = " + money.format(principal)
    				+ "\nInterest Rate = " + (interest_rate * 100) + "%"
    				+ "\nLength of Loan = " + Math.round(number_of_years * 12.0)
    				+ " months" + "\nMonthly Payment = "
    				+ money.format(monthly_payment)); 
                    
                    GraphArea.append("" + principalPaid);
    													// monthlyPayment
    	}
    	
    // This the Scroll pane for the table - sets the boundaries//
        public JScrollPane getScrollPane() {
            if (scrollingTable == null) {
                scrollingTable = new JScrollPane();
                scrollingTable.setBounds(65, 225, 425, 120);
                scrollingTable.setViewportView(getTable());
            }
            return scrollingTable;
        }
    
        public JTable getTable() {
            if (totalAmounts == null) {
                    totalAmounts = new MyJTable(getModel());
            }
            return totalAmounts;
        }
    	 
    	
    	
    //This will calculate the model for the table//
        public MyDTableModel getModel() {
            String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};
    
            model = null;
            model = new MyDTableModel();
            for (int i = 0; i < 6; i++) {
                model.addColumn(columnNames[i]);
            }
    
            // This is the necessary data to calculate the table
            if (principal > 0 && rate != 0 && numberYears != 0) {
                double new_principal = principal;
                NumberFormat nf = NumberFormat.getCurrencyInstance();
                for (int i = 0; i < totalMonths; i++) {
                    Object data[] = new Object[6];
                    data[0] = Integer.toString(i + 1);
                    data[1] = nf.format(new_principal);
                    data[2] = nf.format(monthlyPayment);
                    data[3] = nf.format(interestPaid = principal * monthlyRate);
                    data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
                    data[5] = nf.format(principal = principal - principalPaid);
                    new_principal = principal;
    
                    model.addRow(data);
                }
            }
            return model;
    		  
    		
        }
    	 
    	 public double getDouble(String val) {
    		double value = 00;
    		try {
    			// This tests to see if there is a dollar sign
    			if (val.indexOf('$') > -1) {
    
    				value = NumberFormat.getCurrencyInstance().parse(val)
    						.doubleValue();
    			} else {
    				value = NumberFormat.getNumberInstance().parse(val)
    						.doubleValue();
    			}
    		} catch (java.text.ParseException e) {
    
    			// Generates an error here
    
    			JOptionPane.showMessageDialog(this, "There is an error " + val
    					+ ". Please check your entry", "Data Entry Error",
    					JOptionPane.ERROR_MESSAGE);
    		}
    		return value;
    	}
    
    	public double getPercent(String val) {
    		boolean isPercent = false;
    		double value = 0;
    		try {
    			if (val.indexOf('%') > -1) {
    				value = NumberFormat.getPercentInstance().parse(val)
    						.doubleValue();
    				isPercent = true;
    			} else {
    				value = NumberFormat.getNumberInstance().parse(val)
    						.doubleValue();
    			}
    		} catch (java.text.ParseException e) {
    			JOptionPane.showMessageDialog(this, "There is an error " + val
    					+ ". Please check your entry", "Data Entry Error",
    					JOptionPane.ERROR_MESSAGE);
    		}
    
    		// Have a percentage already in decimal format
    		if (!isPercent)
    			value = value / 100.0;
    
    
    
    		return value;
    	}
    	
    
    	 
    //main() method//
    
    	public static void main(String[] args) {
                
                       
                
    		// Using Nimbus "Look and Feel" to make the layout more appealing.
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            }
            
            
            SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    MortgageCalc thisClass = new MortgageCalc();
                    thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    thisClass.setVisible(true);
                }
            });
            
        }
    
        class MyDTableModel extends DefaultTableModel {
    
            public Class<? extends Object> getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            }
        }
    
        //This class adds the table to the JFrame
        class MyJTable extends JTable {
    
            public MyJTable(){
                super();
            }
    
            public MyJTable(DefaultTableModel m){
                super(m);
    
            }
    
        }
            
        //used to hide and show the correct components
            public void displaySelectionTwo() {  
            
                    chooseCombo.setVisible(false);
    		selectionTwo.setSelected(true);
    		selectionOne.setSelected(false);
    		yearsLabel.setVisible(true);
                    yearsLabel.setText("Loan Term Years:    ");
    		yearsText.setVisible(true);
                    yearsText.setEditable(true);
    		rateText.setVisible(true);
                    rateText.setEditable(true);
    		rateLabel.setVisible(true);
                    chooseLabel.setVisible(false);
                    rateLabel.setText("Interest Rate     :");
    		
            }
            public void hideSelectionTwo() {
    		chooseCombo.setVisible(true);
    		selectionTwo.setSelected(false);
    		selectionOne.setSelected(true);
    		principalLabel.setText("Please Select Loan:   ");
    		rateLabel.setVisible(false);
    		yearsLabel.setText("Years:     ");
                    yearsLabel.setVisible(false);
                    yearsText.setVisible(false);
    		yearsText.setColumns(10);
    		rateLabel.setText("Interest Rate:    ");
                    rateLabel.setVisible(false);
    		rateText.setVisible(false);
                    yearsText.setColumns(10);
                    chooseLabel.setVisible(true);
    		}
            public void drawGraph() // this will draw the graph "somehow"
            {
                
            }
    
            public class GraphProgram extends JPanel
    
    	{
    		GraphProgram.GraphCanvas graph = new GraphProgram.GraphCanvas();
    
    		public GraphProgram()
    		{
    			setLayout(new BorderLayout());
    			setSize(300, 300);
    
    			add(graph, BorderLayout.CENTER);
    		}
    
    		public  void setValues(double[] values) {
    			graph.setValues(values);
    		}
    		public class CoordCanvas extends Canvas
    		{
    			protected float viewLeft;
    			protected float viewRight;
    			protected float viewTop;
    			protected float viewBottom;
    
    			public void setXRange(float left, float right)
    			{
    				viewLeft = left;
    				viewRight = right;
    			}
    
    			public void setYRange(float top, float bottom)
    			{
    				viewTop = top;
    				viewBottom = bottom;
    			}
    
    			public float toX(float x)
    			{
    				return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
    			}
    
    			public float toY(float y)
    			{
    				return (y - viewTop) * getSize().height / (viewBottom - viewTop);
    			}
    
    			public float toWidth(float w)
    			{
    				return w * getSize().width / Math.abs(viewRight - viewLeft);
    			}
    
    			public float toHeight(float h)
    			{
    				return h * getSize().height / Math.abs(viewBottom - viewTop);
    			}
    		}
    
    
    		//  subclass to draw a bar graph
    
    		class GraphCanvas extends GraphProgram.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, (float)vals.length);
    				this.setYRange((float)max, 0F);
    
    				// draw the graph
    				Graphics2D comp2D = (Graphics2D)comp;
    				for (int i = 0; i < vals.length; i++)
    				{
    					Rectangle2D.Float principal = new Rectangle2D.Float(toX((float)i),
    							toY((float)vals[i]), toWidth(1F), toHeight((float)vals[i]));
    					comp2D.fill(principal);
    				}
    			}
    			
    		}
    	
            }
            
    	
    }

  2. #2
    thelgar is offline DeathBringer
    Join Date
    Jan 2012
    Location
    California
    Posts
    4
    Rep Power
    0

    Default Re: Help with graphs

    sorry. correction:

    Add graphics in the form of a chart that displays the change in principal balance over the life of the loan.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: Help with graphs

    here is what i have, could really use some help completing it.
    Then hire some. This is a forum, not a coding service. Posting 700+ lines of code without a specific question won't get you anywhere here.

    Recommended reading: How to ask questions the smart way

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    thelgar is offline DeathBringer
    Join Date
    Jan 2012
    Location
    California
    Posts
    4
    Rep Power
    0

    Default Re: Help with graphs

    ok my SPECIFIC question is, what am i missing? my code seems to be there, from what the instructor and book are telling me, but no graph is showing up. i tried creating a button and clicking it to make a graph show up but i couldn't get it to work. could someone please explain what i am missing?

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Help with graphs

    That's a lot of code to expect volunteers to go through, so I will give general suggestions. First and foremost, try to solve each issue in the small not in the large. In other words, subdivide the tasks needed to solve your problem and solve each class in its own small class/program before combining it into the large finished program. This way you (and we) only have to debug small bits of fully self-contained code, rather than a large huge program with most code unrelated to your problem. Next, sprinkle your unfinished code with System.out.println(...) statements that tell you the state of key variables as the program runs. You will get rid of these before submitting the finished product.

    For your specific example, I would create a class that does nothing but calculate the data given the initial conditions. This could produce an ArrayList of a certain data type, say perhaps MortgageRow, that stands for a row of data on a mortgage table. This class would contain no GUI code whatsoever, but would have a constructor that took in the data required to calculate the mortgage and then would return the ArrayList / mortgage table. This class is your model

    You'll want a GUI class of course, a class that creates the JFrame, adds the buttons, the JPanels and the what nots and allows the buttons to talk to the model. This would be your view-control (I'm combining view and control given the relatively small size of this project).

    You'll also want to create a painting JPanel with a paintComponent override that allows you to visualize your data graphically. You should be able to pass your ArrayList<MortgageRow> into this class, call repaint and visualize the data -- and that is how you should test this class: feed it a ready-made arraylist and see what happens. Then if you get stuck, you can post your smaller self-contained graphing class and we can better be able to help you with it.
    Last edited by Fubarable; 01-28-2012 at 04:30 PM.

  6. #6
    thelgar is offline DeathBringer
    Join Date
    Jan 2012
    Location
    California
    Posts
    4
    Rep Power
    0

    Default Re: Help with graphs

    Fubarable,
    thanks for the advice. I am sure my problem lays in 2 main areas.
    1) i cannot seem to figure out how to call the graph in my program. i have tried calling the pain method and hte graph methods but nothing happens.
    2) i don't understand how to create a new window in java to place the code in.

    i am not possitive but i believe my problem is in this area.

    Java Code:
    public void drawGraph() // this will draw the graph "somehow"
            {
                
            }
    
            class GraphCanvas extends Canvas
    {
    
    	public GraphCanvas()
    	{
    		setSize(450, 150);
    	}
    
    	protected int viewLeft;
    	protected int viewRight;
    	protected int viewTop;
    	protected int viewBottom;
    
    	public void setXRange(int left, int right)
    	{
    		viewLeft = left;
    	    viewRight = right;
    	}
    
    	public void setYRange(int top, int bottom)
    	{
    	    viewTop = top;
    	    viewBottom = bottom;
    	}
    
    	public int toX(int x)
    	{
    	    return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
    	}
    
    	public int toY(int y)
    	{
    	    return (y - viewTop) *
    	    getSize().height / (viewBottom - viewTop);
    	}
    
    	public int toWidth(int w)
    	{
    	    return (w * getSize().width /
    	    Math.abs(viewRight - viewLeft));
    	}
    
    	public int toHeight(int h)
    	{
    	    return (h * getSize().height /
    	    Math.abs(viewBottom - viewTop));
    	}
    
    	public void paint(Graphics g) // display shapes on canvas
    	{
    		// draw entire component with blue border and label
    		g.setColor(Color.red);
    		g.drawRect(0, 0, 449, 134);
    		g.drawString("Principle Graph", 180, 20);
    
    		int [] amount;
    		amount = new int [360];
    
    		setXRange(0, 360);
    		setYRange(200000, 0);
    
    		for (int n=0; n<360; n++)
    		{
        	g.drawLine(toX(n),toY(amount[n]),toWidth(1),toHeight(amount[n]));
    
    		}
    
    	}
    
    }

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Help with graphs

    Please see the edit to my post above. Again, you'll want to post code that is fully self-contained.

    Also please don't extend Canvas with a Swing program. Your reading should have already told you this. Extend JPanel and paint in its paintComponent method, not the paint method. And the first method call in paintComponent should be super.paintComponent(g).
    DarrylBurke likes this.

Similar Threads

  1. graphs in java
    By divyan in forum Advanced Java
    Replies: 3
    Last Post: 03-04-2011, 01:35 PM
  2. JSP charts and graphs
    By maas in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 11-29-2010, 10:28 AM
  3. Graphs and if else statement
    By MapleLeafRag in forum New To Java
    Replies: 1
    Last Post: 12-03-2009, 10:56 PM
  4. Graphs
    By siddharth_s_b in forum NetBeans
    Replies: 1
    Last Post: 05-22-2008, 04:12 AM
  5. Graphs
    By javaplus in forum Advanced Java
    Replies: 1
    Last Post: 12-07-2007, 09:17 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •