Results 1 to 20 of 20
  1. #1
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Angry Problems with JTable / JPanel

    Hello all,

    This is my first post on this forum and I am new to Java - so play nice. I am creating a project for school and I am stuck beyond belief. Our program is to create an amortization table using a GUI. We have done this project before without a GUI, so I just wanted to use what I already had and adapt it to a GUI. Since I am printing out an amortization table on the screen, I wanted to use JTable to make it nice and neat. However, I can't get the data[][] object to work right. Any help would be greatly appreciated.

    Java Code:
        public static void amortizeLoan(double LoanBalance,double monthlyPayment,int numPayments,double interestRate){
            
            JFrame frame=new JFrame();
            frame.setSize(500,500);
            
            String[] columnNames={"Payment #","Loan Balance","Principal:","Interest Paid"};
            
            DecimalFormat money=new DecimalFormat("$0.00");           // Set the format for money
            double loanBalance=LoanBalance;                           // Copy the loan balance that is brought in
            double interestPaid=LoanBalance*interestRate/12;          // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                System.out.print("#: "+num+"      Bal: "+money.format(loanBalance) +"      Principal: "+money.format(principalPaid) +"      Int: "+money.format(interestPaid)+"\n");
                Object[][] data={{num,money.format(loanBalance),money.format(principalPaid),money.format(interestPaid)}};
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*interestRate/12;
                principalPaid=monthlyPayment-interestPaid;
    
                // Wait one quarter of a second between entries
                wait.quarterSec();
            }
            return;
            JTable table=new JTable(data,columnNames);
            
            JScrollPane scrollPane=new JScrollPane(table);
            table.setFillsViewportHeight(true);
            
            frame.add(scrollPane);
            frame.setVisible(true);
        }
    This sub is called with three different loan values successively using an array. The monthlyPayments and interestRate are the only things that change. If you need more info, please let me know.

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

    Default

    Hello and welcome to the forum. If your code generates any errors, you're best to post the actual error messages. Just looking at it, I'll bet that it doesn't compile as there's a return statement mid-method, and all the code below it is non-reachable. You might want to get rid of that. Also, I don't think that that wait.quarterSec() is going to do you any good here either. Also, you'll want to declare the data 2D object array before the for loop so that it is visible after the loop and so you don't erase previous values with each iteration of the loop but rather fill the already existing array with each iteration.

    Best of luck and hope this helps.

  3. #3
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Hello and welcome to the forum. If your code generates any errors, you're best to post the actual error messages. Just looking at it, I'll bet that it doesn't compile as there's a return statement mid-method, and all the code below it is non-reachable. You might want to get rid of that. Also, I don't think that that wait.quarterSec() is going to do you any good here either. Also, you'll want to declare the data 2D object array before the for loop so that it is visible after the loop and so you don't erase previous values with each iteration of the loop but rather fill the already existing array with each iteration.

    Best of luck and hope this helps.
    Actually, it compiles just fine. However, I get three windows showing only the first payment in each loan.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    Have you tried to compile the code you posted? I get the following errors when I try:
    TestCompile1.java:34: cannot find symbol
    symbol : variable data
    location: class TestCompile1
    JTable table=new JTable(data,columnNames);
    ^
    TestCompile1.java:40: unreachable statement
    Can you find and post code that will compile?

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

    Default

    Quote Originally Posted by mbutler755 View Post
    Actually, it compiles just fine.
    Then please post your real code. The code you've posted will not compile. Period.

    However, I get three windows showing only the first payment in each loan.
    Again, without your real code, we can't help you.

  6. #6
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Then please post your real code. The code you've posted will not compile. Period.


    Again, without your real code, we can't help you.
    This is some altered code that I was working on. Unfortunately, this gives me too many windows because of the way that the method is called.

    Java Code:
    package wk3mbutler;
    
    /**
     * Matt Butler
     * Week 3 - Individual Project
     */
    
    // Imports for the program
    import java.text.DecimalFormat;			// Import decimal format
    import java.awt.event.ActionEvent;		// Import for ActionEvent
    import java.awt.event.ActionListener;           // Import for ActionListener
    import javax.swing.JFrame;			// Import for JFrame
    import javax.swing.JPanel;			// Import for JPanel
    import javax.swing.JTextField;			// Import for JTextField
    import javax.swing.JButton;			// Import for JButton
    import javax.swing.JLabel;			// Import for JLabel
    import java.awt.GridLayout;                     // Import for the GridLayout
    import java.awt.Container;                      // Import for the GridLayout Container
    import javax.swing.JTable;
    import java.awt.ScrollPane;
    import javax.swing.JScrollPane;
    import java.awt.BorderLayout;
    
    // start of Main
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // Define what money should look like
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // declare some variables for the program
            int totalMortgage=0;						// Total Mortgage amount
            int loanLengthInYears=0;					// Loan length in years
            int loanLengthInMonths=loanLengthInYears*12;			// Loan length in months = loan length in years / 12 months
            double annualInterestRate=0;					// Annual Interest Rate
            double monthlyInterestRate=(annualInterestRate/100)/12;		// Monthly interest rate = annual interest rate / 12 months
    
            // Setting up the window
            JFrame myWindow=new JFrame("Matt's Calculator");		// Setup a new frame and name it
            int windowWidth=400;						// define the window width
            int windowHeight=175;						// define the window height
            myWindow.setBounds(100,100, windowWidth, windowHeight);		// set the bounds of the window
            myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	// set the 'x' to close & terminate the program when pushed
            myWindow.setVisible(true);					// set the window's visible property to true
    
            // Set up the panel
            JPanel myPanel=new JPanel();
            
            // Set up a grid layout
            GridLayout myLayout=new GridLayout(3,2,2,2);                    // Setup the grid layout
            Container content=myWindow.getContentPane();                    // Create a container and get the content pane
            content.setLayout(myLayout);                                    // Set the layout to the layout created
            
            // define the labels and text fields
            JLabel lblMortgageAmount=new JLabel(" Mortgage Amount: ",JLabel.RIGHT);     // Create a label for the mortgage amount
            final JTextField txtMortgageAmount=new JTextField(16);                      // Create a text field for the mortgage amount
            
            // Set up the Calculate button and a listener
            // for the button.
            JButton CalcButton=new JButton("Calculate Payment");		// Create a button to calculate the payments
            class calcLoanListener implements ActionListener{		// setup a listener for the calculate payment button
                public void actionPerformed(ActionEvent event){		// setup the event for the program to execute when the button is clicked
    
                    int loanAmount=Integer.parseInt(txtMortgageAmount.getText());
    
                    // Declare and initalize the arrays
                    int[] loanYears=new int[3];
                    double[] interestRate=new double[3];
    
                    // Fill the arrays
                    //   Loan 1: 07 years @ 5.35% interest
                    //   Loan 2: 15 years @ 5.50% interest
                    //   Loan 3: 30 years @ 5.75% interest
                    loanYears[0]=7;
                    loanYears[1]=15;
                    loanYears[2]=30;
                    interestRate[0]=5.35;
                    interestRate[1]=5.5;
                    interestRate[2]=5.75;
    
                    // This is the while loop that iterates through the elements of the array
                    // and then calls the method to calculate the loan information for the
                    // specific elements in question.
                    int count=0;
                    while (count != loanYears.length) {
                        loanCalcs.calculateLoan(loanAmount, interestRate[count], loanYears[count]);
                        count++;
                    } //end the while loop
                } // end actionPerformed
            } // end subclass calcLoanListener
            ActionListener myListener=new calcLoanListener();
            CalcButton.addActionListener(myListener);
    
            JButton clearButton=new JButton("Clear");
            class clearButtonListener implements ActionListener{
                public void actionPerformed(ActionEvent event){
                    txtMortgageAmount.setText("");
                } // end actionPerformed
            } // end subclass clearButtonListener
            ActionListener clearButtonListener=new clearButtonListener();
            clearButton.addActionListener(clearButtonListener);
    
            // Add the items to the panel
            myWindow.add(lblMortgageAmount);	// add the lblMortgageAmount to the window
            myWindow.add(txtMortgageAmount);	// add the txtMortgageAmount to the window
            myWindow.add(CalcButton);		// add the calculate button to the window
            myWindow.add(clearButton);
    
            // Add the panel to the window
            myWindow.add(myPanel);
    
        } // end main
    } // end class
    
    //Start of class wait
    class wait {
    
        // Gives me the ability to halt execution for one quarter of a second
        public static void quarterSec() {
            try {
                Thread.currentThread().sleep(250);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
    
        // Gives me the ability to halt execution for one second
        public static void oneSec() {
            try {
                Thread.currentThread().sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        // Gives me the ability to halt the execution for a specified amount of time
        public static void manySec(long s) {
            try {
                Thread.currentThread().sleep(s * 1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } //End class wait
    
    // Start of loan calculations class
    class loanCalcs {
        // Calculate the basic loan information
        public static void calculateLoan(int mortgageAmount,double interestRate,int yearsOfLoan){
            // Define what money should look like
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // Create and set some variables for the program
            int totalMortgage=mortgageAmount;                     // Set the amount of the total mortgage
            int loanLengthInYears=yearsOfLoan;                    // Set the loan length the variable of the constructor
            int loanLengthInMonths=loanLengthInYears*12;          // Calculate the total number of monthly payments
            double annualInterestRate=interestRate/100;           // Set the annual interest rate 5.75% / 100 = .0575
            double monthlyInterestRate=annualInterestRate/12;     // Set the monthly interest rate (AnnualInterestRate / 12 months per year)
            double monthlyPayment=0.00;                           // Declare a variable for the monthly payment
    
            // Create the formula to get the monthly mortgage payment
            // with interest
    	monthlyPayment=totalMortgage*(monthlyInterestRate/(1-Math.pow((1+monthlyInterestRate), -1*(loanLengthInMonths))));
    
            // Display the loan information to the user
            System.out.println();
            System.out.println(" Your total financed mortgage : "+money.format(totalMortgage));                         // Show the total amount financed
            System.out.println(" Your annual interest rate is : "+annualInterestRate*100 +"%");                         // Show the annual interest rate as a percentage
            System.out.println(" Total number of payments     : "+loanLengthInMonths);                                  // Total number of payments
            System.out.println(" Your monthly payment is      : "+money.format(monthlyPayment));                        // Show the monthly payment from the formula calculation
            System.out.println();
            loanCalcs.amortizeLoan(totalMortgage, monthlyPayment, loanLengthInMonths,annualInterestRate);
    
        } // end class loanCalcs
    
        // Amortizes the loan
        public static void amortizeLoan(double LoanBalance,double monthlyPayment,int numPayments,double interestRate){
            
            DecimalFormat money=new DecimalFormat("$0.00");           // Set the format for money
            double loanBalance=LoanBalance;                           // Copy the loan balance that is brought in
            double interestPaid=LoanBalance*interestRate/12;          // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                System.out.print("#: "+num+"      Bal: "+money.format(loanBalance) +"      Principal: "+money.format(principalPaid) +"      Int: "+money.format(interestPaid)+"\n");
                loanCalcs.showOutput(num, loanBalance, principalPaid, interestPaid);
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*interestRate/12;
                principalPaid=monthlyPayment-interestPaid;
    
                // Wait one quarter of a second between entries
                wait.quarterSec();
            }
            return;
        }
    
        public static void showOutput(int myPaymentNum,double myLoanBalance,double myPrincipalPaid, double myInterestPaid){
    
            String[] columnNames={"Payment #","Loan Balance","Principal:","Interest Paid"};
            int paymentNumber=myPaymentNum;
            double loanBalance=myLoanBalance;
            double principalPaid=myPrincipalPaid;
            double interestPaid=myInterestPaid;
            Object[][] data={{paymentNumber,loanBalance,principalPaid,interestPaid}};
    
            JFrame frame=new JFrame();
            frame.setSize(500,500);
            JTable table=new JTable(data,columnNames);
            JScrollPane scrollPane=new JScrollPane(table);
            table.setFillsViewportHeight(true);
            frame.add(scrollPane);
            frame.setVisible(true);
        }
    
        static void calculateLoan(String strMortAmount, String strIntRate, String strLoanLength) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        static void calculateLoan(int parseInt, String text, String text0) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        static void calculateLoan(int parseInt, double parseDouble, double parseDouble0) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    } //End class amortize

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    this gives me too many windows
    Can you explain why it gives you the second window
    and then the next window
    and then the next window???

    You must have a reason for having more than one. What is it?
    Without you describing what the program is supposed to do, no one can help you make the program do what you want.

  8. #8
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Can you explain why it gives you the second window
    and then the next window
    and then the next window???

    You must have a reason for having more than one. What is it?
    Without you describing what the program is supposed to do, no one can help you make the program do what you want.
    Exactly. This one gives you one window per line. Ideally, I would like to have three windows total. One window per loan. So, one loan would come out at 5.35% @ 84 months. The next would be 5.5% @ 180 months. The remaining loan would be 5.75% @ 360 months. I want all of the payments for the first loan to be in the first window, the second amount of payments in the second window and so on and so forth.

    My apologies this was not clear. I was playing around with it between my OP and the full code post. The way it is now, is definately not going to work. If I can't get this to run the way that I want it to, I think I might just put it in a JTextArea. Ideally, I would like to have it in a JTable though.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    You still have not answered my question about why the code keeps creating new windows.
    How many windows do you want total?
    What is supposed to go in each window?

    Every time you call showOutput it opens a new window. Why?

  10. #10
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    You still have not answered my question about why the code keeps creating new windows.
    How many windows do you want total?
    What is supposed to go in each window?

    Every time you call showOutput it opens a new window. Why?
    Norm,

    did you read my previous post? It says that I want three windows in total. It also says that I would want one window per loan.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    You still miss answering the question about why you are opening so many windows.
    Especially this question:
    Every time you call showOutput it opens a new window. Why?

  12. #12
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    You still miss answering the question about why you are opening so many windows.
    Especially this question:
    Every time you call showOutput it opens a new window. Why?
    Do you not know why? It's because every time showOutput is called it is creating a new window. I don't want this. I think I am going to have to put it in a JTextArea. The assignment is due tonight. I will just have to fix it.

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    because every time showOutput is called it is creating a new window. I don't want this.
    Yes, you need to redesign the program to open the desired number of windows and use them to show what you want shown in each.

  14. #14
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Yes, you need to redesign the program to open the desired number of windows and use them to show what you want shown in each.
    Gee Norm. Any ideas on the best way to do this?

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    You want to have three windows. What do you want displayed in each window?
    What classes and methods do you need to support displaying that data in each window?
    Perhaps have a class for each window that takes care of opening, displaying and clearing the data.

  16. #16
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Perhaps have a class for each window that takes care of opening, displaying and clearing the data.
    Now that is an idea. I will code it and see how it pans out. Good job Norm!

  17. #17
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Cool

    Quote Originally Posted by Norm View Post
    Perhaps have a class for each window that takes care of opening, displaying and clearing the data.
    This works perfectly Norm. Take a look and tell me what you think. Put in a loan value of 200000

    Java Code:
    package wk3mbutler;
    
    /**
     * Matt Butler
     * Week 3 - Individual Project
     */
    
    // Imports for the program
    import java.text.DecimalFormat;			// Import decimal format
    import java.awt.event.ActionEvent;		// Import for ActionEvent
    import java.awt.event.ActionListener;           // Import for ActionListener
    import javax.swing.JFrame;			// Import for JFrame
    import javax.swing.JPanel;			// Import for JPanel
    import javax.swing.JTextField;			// Import for JTextField
    import javax.swing.JButton;			// Import for JButton
    import javax.swing.JLabel;			// Import for JLabel
    import java.awt.GridLayout;                     // Import for the GridLayout
    import java.awt.Container;                      // Import for the GridLayout Container
    import javax.swing.JScrollPane;                 // Import for JScrollPane
    import javax.swing.JTextArea;                   // Import for JTextArea
    import javax.swing.JOptionPane;                 // Import for JOptionPane
    
    // start of Main
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // Define what money should look like
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // declare some variables for the program
            int totalMortgage=0;						// Total Mortgage amount
            int loanLengthInYears=0;					// Loan length in years
            int loanLengthInMonths=loanLengthInYears*12;			// Loan length in months = loan length in years / 12 months
            double annualInterestRate=0;					// Annual Interest Rate
            double monthlyInterestRate=(annualInterestRate/100)/12;		// Monthly interest rate = annual interest rate / 12 months
    
            // Setting up the window
            JFrame myWindow=new JFrame("Matt's Calculator");		// Setup a new frame and name it
            int windowWidth=400;						// define the window width
            int windowHeight=175;						// define the window height
            myWindow.setBounds(100,100, windowWidth, windowHeight);		// set the bounds of the window
            myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	// set the 'x' to close & terminate the program when pushed
            myWindow.setVisible(true);					// set the window's visible property to true
    
            // Set up the panel
            JPanel myPanel=new JPanel();
            
            // Set up a grid layout
            GridLayout myLayout=new GridLayout(3,2,2,2);                    // Setup the grid layout
            Container content=myWindow.getContentPane();                    // Create a container and get the content pane
            content.setLayout(myLayout);                                    // Set the layout to the layout created
            
            // define the labels and text fields
            JLabel lblMortgageAmount=new JLabel(" Mortgage Amount: ",JLabel.RIGHT);     // Create a label for the mortgage amount
            final JTextField txtMortgageAmount=new JTextField(16);                      // Create a text field for the mortgage amount
            
            // Set up the Calculate button and a listener
            // for the button.
            JButton CalcButton=new JButton("Calculate Payment");		// Create a button to calculate the payments
            class calcLoanListener implements ActionListener{		// setup a listener for the calculate payment button
                public void actionPerformed(ActionEvent event){		// setup the event for the program to execute when the button is clicked
    
                    int loanAmount=Integer.parseInt(txtMortgageAmount.getText());
    
                    // Declare and initalize the arrays
                    int[] loanYears=new int[3];
                    double[] interestRate=new double[3];
    
                    // Fill the arrays
                    //   Loan 1: 07 years @ 5.35% interest
                    //   Loan 2: 15 years @ 5.50% interest
                    //   Loan 3: 30 years @ 5.75% interest
                    loanYears[0]=7;
                    loanYears[1]=15;
                    loanYears[2]=30;
                    interestRate[0]=5.35;
                    interestRate[1]=5.5;
                    interestRate[2]=5.75;
    
                    // This is the while loop that iterates through the elements of the array
                    // and then calls the method to calculate the loan information for the
                    // specific elements in question.
                    int count=0;
                    while (count != loanYears.length) {
                        guiLoans.showOutput(loanAmount, interestRate[count], loanYears[count]);
                        count++;
                    } //end the while loop
                } // end actionPerformed
            } // end subclass calcLoanListener
            ActionListener myListener=new calcLoanListener();
            CalcButton.addActionListener(myListener);
    
            JButton clearButton=new JButton("Clear");
            class clearButtonListener implements ActionListener{
                public void actionPerformed(ActionEvent event){
                    txtMortgageAmount.setText("");
                } // end actionPerformed
            } // end subclass clearButtonListener
            ActionListener clearButtonListener=new clearButtonListener();
            clearButton.addActionListener(clearButtonListener);
    
            // Add the items to the panel
            myWindow.add(lblMortgageAmount);	// add the lblMortgageAmount to the window
            myWindow.add(txtMortgageAmount);	// add the txtMortgageAmount to the window
            myWindow.add(CalcButton);		// add the calculate button to the window
            myWindow.add(clearButton);
    
            // Add the panel to the window
            myWindow.add(myPanel);
    
        } // end main
    } // end class
    
    //Start of class wait
    class wait {
    
        // Gives me the ability to halt execution for one quarter of a second
        public static void quarterSec() {
            try {
                Thread.currentThread().sleep(250);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
    
        // Gives me the ability to halt execution for one second
        public static void oneSec() {
            try {
                Thread.currentThread().sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        // Gives me the ability to halt the execution for a specified amount of time
        public static void manySec(long s) {
            try {
                Thread.currentThread().sleep(s * 1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } //End class wait
    
    // Start of loan calculations class
    class loanCalcs {
        // Calculate the basic loan information
        public static void calculateLoan(int mortgageAmount,double interestRate,int yearsOfLoan){
            // Define what money should look like
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // Create and set some variables for the program
            int totalMortgage=mortgageAmount;                     // Set the amount of the total mortgage
            int loanLengthInYears=yearsOfLoan;                    // Set the loan length the variable of the constructor
            int loanLengthInMonths=loanLengthInYears*12;          // Calculate the total number of monthly payments
            double annualInterestRate=interestRate/100;           // Set the annual interest rate 5.75% / 100 = .0575
            double monthlyInterestRate=annualInterestRate/12;     // Set the monthly interest rate (AnnualInterestRate / 12 months per year)
            double monthlyPayment=0.00;                           // Declare a variable for the monthly payment
    
            // Create the formula to get the monthly mortgage payment
            // with interest
    	monthlyPayment=totalMortgage*(monthlyInterestRate/(1-Math.pow((1+monthlyInterestRate), -1*(loanLengthInMonths))));
    
            // Display the loan information to the user
            System.out.println();
            System.out.println(" Your total financed mortgage : "+money.format(totalMortgage));                         // Show the total amount financed
            System.out.println(" Your annual interest rate is : "+annualInterestRate*100 +"%");                         // Show the annual interest rate as a percentage
            System.out.println(" Total number of payments     : "+loanLengthInMonths);                                  // Total number of payments
            System.out.println(" Your monthly payment is      : "+money.format(monthlyPayment));                        // Show the monthly payment from the formula calculation
            System.out.println();
            loanCalcs.amortizeLoan(totalMortgage, monthlyPayment, loanLengthInMonths,annualInterestRate);
    
        } // end class loanCalcs
    
        // Amortizes the loan
        public static void amortizeLoan(double LoanBalance,double monthlyPayment,int numPayments,double interestRate){
            
            DecimalFormat money=new DecimalFormat("$0.00");           // Set the format for money
            double loanBalance=LoanBalance;                           // Copy the loan balance that is brought in
            double interestPaid=LoanBalance*interestRate/12;          // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                System.out.print("#: "+num+"      Bal: "+money.format(loanBalance) +"      Principal: "+money.format(principalPaid) +"      Int: "+money.format(interestPaid)+"\n");
    
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*interestRate/12;
                principalPaid=monthlyPayment-interestPaid;
                // Wait one quarter of a second between entries
                wait.quarterSec();
            } // end for loop
            return;
        } //end amortize loan calcs
    } //End class amortize
    
    class guiLoans{
        public static void showOutput(int mortgageAmount,double interestRate,int yearsOfLoan){
    
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // Create and set some variables for the program
            int totalMortgage=mortgageAmount;                     // Set the amount of the total mortgage
            int loanLengthInYears=yearsOfLoan;                    // Set the loan length the variable of the constructor
            int loanLengthInMonths=loanLengthInYears*12;          // Calculate the total number of monthly payments
            double annualInterestRate=interestRate/100;           // Set the annual interest rate 5.75% / 100 = .0575
            double monthlyInterestRate=annualInterestRate/12;     // Set the monthly interest rate (AnnualInterestRate / 12 months per year)
            double monthlyPayment=0.00;                           // Declare a variable for the monthly payment
    
            // Create the formula to get the monthly mortgage payment
            // with interest
    	monthlyPayment=totalMortgage*(monthlyInterestRate/(1-Math.pow((1+monthlyInterestRate), -1*(loanLengthInMonths))));
    
            // Create some JOptionPanes and display loan summaries before the amortization is displayed
            JOptionPane loanSummary=new JOptionPane();
            loanSummary.showMessageDialog(loanSummary, "For a "+money.format(mortgageAmount) +" with a " +interestRate +"% interest rate\nfor "+loanLengthInYears +" years, it would cost "+money.format(monthlyPayment)+" per month.");
    
            // Set up a frame and a scroll pane to add the results of the amortization
            JFrame frame=new JFrame();
            frame.setSize(500, 500);
            JScrollPane scrollPane=new JScrollPane();
            JTextArea resultsArea=new JTextArea();
            scrollPane.setViewportView(resultsArea);
            frame.add(scrollPane);
            frame.setVisible(true);
            frame.setTitle(money.format(totalMortgage)+" @ "+interestRate +"% for "+loanLengthInYears +" years");
            resultsArea.setEditable(false);
    
            DecimalFormat paymentMoney=new DecimalFormat("$0.00");    // Set the format for money
            int numPayments=yearsOfLoan*12;                           // get the numPayments by multiplying the loanLengthInYears by 12 months
            double loanBalance=totalMortgage;                         // Copy the loan balance that is brought in
            double interestPaid=loanBalance*(interestRate/100)/12;    // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                resultsArea.append("#: "+num+"      Bal: "+paymentMoney.format(loanBalance) +"      Principal: "+paymentMoney.format(principalPaid) +"      Int: "+paymentMoney.format(interestPaid)+"\n");
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*(interestRate/100)/12;
                principalPaid=monthlyPayment-interestPaid;
            } // end for loop
        } // end showOutput
    } // end class guiLoans
    Last edited by mbutler755; 09-30-2010 at 05:13 AM. Reason: Which loan value??

  18. #18
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    While my previous post works great, I still have my heart set on using the JTable. I plugged in the following code, but I am having a problem with the data object since it is inside of the For loop. Any ideas on how I can fix this would be much appreciated.

    Java Code:
    class guiLoans{
        public static void showOutput(int mortgageAmount,double interestRate,int yearsOfLoan){
    
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // Create and set some variables for the program
            int totalMortgage=mortgageAmount;                     // Set the amount of the total mortgage
            int loanLengthInYears=yearsOfLoan;                    // Set the loan length the variable of the constructor
            int loanLengthInMonths=loanLengthInYears*12;          // Calculate the total number of monthly payments
            double annualInterestRate=interestRate/100;           // Set the annual interest rate 5.75% / 100 = .0575
            double monthlyInterestRate=annualInterestRate/12;     // Set the monthly interest rate (AnnualInterestRate / 12 months per year)
            double monthlyPayment=0.00;                           // Declare a variable for the monthly payment
    
            // Create the formula to get the monthly mortgage payment
            // with interest
    	monthlyPayment=totalMortgage*(monthlyInterestRate/(1-Math.pow((1+monthlyInterestRate), -1*(loanLengthInMonths))));
    
            // Create some JOptionPanes and display loan summaries before the amortization is displayed
            JOptionPane loanSummary=new JOptionPane();
            loanSummary.showMessageDialog(loanSummary, "For a "+money.format(mortgageAmount) +" with a " +interestRate +"% interest rate\nfor "+loanLengthInYears +" years, it would cost "+money.format(monthlyPayment)+" per month.");
    
            // Set up a frame and a scroll pane to add the results of the amortization
            JFrame frame=new JFrame();
            frame.setSize(500, 500);
            JScrollPane scrollPane=new JScrollPane();
            JTextArea resultsArea=new JTextArea();
            scrollPane.setViewportView(resultsArea);
            frame.add(scrollPane);
            frame.setVisible(true);
            frame.setTitle(money.format(totalMortgage)+" @ "+interestRate +"% for "+loanLengthInYears +" years");
            resultsArea.setEditable(false);
    
    	JFrame testFrame=new JFrame();
    	testFrame.setSize(600,600);
    	JScrollPane testScrollPane=new JScrollPane();
    	String[] columnNames={"Payment #","Balance","Principal","Interest"};
    
            DecimalFormat paymentMoney=new DecimalFormat("$0.00");    // Set the format for money
            int numPayments=yearsOfLoan*12;                           // get the numPayments by multiplying the loanLengthInYears by 12 months
            double loanBalance=totalMortgage;                         // Copy the loan balance that is brought in
            double interestPaid=loanBalance*(interestRate/100)/12;    // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                resultsArea.append("#: "+num+"      Bal: "+paymentMoney.format(loanBalance) +"      Principal: "+paymentMoney.format(principalPaid) +"      Int: "+paymentMoney.format(interestPaid)+"\n");
                [B]Object[][] data={{num,paymentMoney.format(loanBalance),paymentMoney.format(principalPaid),paymentMoney.format(interestPaid)}};[/B]
    
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*(interestRate/100)/12;
                principalPaid=monthlyPayment-interestPaid;
            } // end for loop
            JTable testTable=new JTable([B]data[/B], columnNames);
    	testScrollPane.setViewportView(testTable);
    	testFrame.add(testScrollPane);
    	testFrame.setVisible(true);
        } // end showOutput

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default

    but I am having a problem with the data object
    What is the problem?

    If it is a scope problem, move the definition of the variable out of the {}s until it is at the same level as where you need it.

  20. #20
    mbutler755 is offline Member
    Join Date
    Jul 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    What is the problem?

    If it is a scope problem, move the definition of the variable out of the {}s until it is at the same level as where you need it.
    BOOYA!!

    Java Code:
    class guiLoans{
        public static void showOutput(int mortgageAmount,double interestRate,int yearsOfLoan){
    
            DecimalFormat money=new DecimalFormat("$0,000.00");
    
            // Create and set some variables for the program
            int totalMortgage=mortgageAmount;                     // Set the amount of the total mortgage
            int loanLengthInYears=yearsOfLoan;                    // Set the loan length the variable of the constructor
            int loanLengthInMonths=loanLengthInYears*12;          // Calculate the total number of monthly payments
            double annualInterestRate=interestRate/100;           // Set the annual interest rate 5.75% / 100 = .0575
            double monthlyInterestRate=annualInterestRate/12;     // Set the monthly interest rate (AnnualInterestRate / 12 months per year)
            double monthlyPayment=0.00;                           // Declare a variable for the monthly payment
    
            // Create the formula to get the monthly mortgage payment
            // with interest
    	monthlyPayment=totalMortgage*(monthlyInterestRate/(1-Math.pow((1+monthlyInterestRate), -1*(loanLengthInMonths))));
    
            // Create some JOptionPanes and display loan summaries before the amortization is displayed
            JOptionPane loanSummary=new JOptionPane();
            loanSummary.showMessageDialog(loanSummary, "For a "+money.format(mortgageAmount) +" with a " +interestRate +"% interest rate\nfor "+loanLengthInYears +" years, it would cost "+money.format(monthlyPayment)+" per month.");
    
            // Set up a frame and a scroll pane to add the results of the amortization
            //JFrame frame=new JFrame();
            //frame.setSize(500, 500);
            //JScrollPane scrollPane=new JScrollPane();
            //JTextArea resultsArea=new JTextArea();
            //scrollPane.setViewportView(resultsArea);
            //frame.add(scrollPane);
            //frame.setVisible(true);
            //frame.setTitle(money.format(totalMortgage)+" @ "+interestRate +"% for "+loanLengthInYears +" years");
            //resultsArea.setEditable(false);
    
    	JFrame testFrame=new JFrame();
    	testFrame.setSize(600,600);
    	JScrollPane testScrollPane=new JScrollPane();
    	
    	DefaultTableModel model=new DefaultTableModel();
            DecimalFormat paymentMoney=new DecimalFormat("$0.00");    // Set the format for money
            int numPayments=yearsOfLoan*12;                           // get the numPayments by multiplying the loanLengthInYears by 12 months
            double loanBalance=totalMortgage;                         // Copy the loan balance that is brought in
            double interestPaid=loanBalance*(interestRate/100)/12;    // Set the interest paid
            double principalPaid=monthlyPayment-interestPaid;         // Set the principal paid
            JTable testTable=new JTable(model);
            testScrollPane.setViewportView(testTable);
    	testFrame.add(testScrollPane);
    	testFrame.setVisible(true);
            testFrame.setTitle(money.format(totalMortgage)+" @ "+interestRate +"% for "+loanLengthInYears +" years = " +money.format(monthlyPayment) +"/mo");
            model.addColumn("Payment #");
            model.addColumn("Balance");
            model.addColumn("Principal");
            model.addColumn("Interest Paid");
            
            for (int num=1;num<=numPayments;num++){                   // for loop to loop through all payments to find the balance, principal paid and interest paid
    
                // Print out the payment number, balance, principal paid and interest paid.
                //resultsArea.append("#: "+num+"      Bal: "+paymentMoney.format(loanBalance) +"      Principal: "+paymentMoney.format(principalPaid) +"      Int: "+paymentMoney.format(interestPaid)+"\n");
                model.insertRow(num-1, new Object[]{num,paymentMoney.format(loanBalance),paymentMoney.format(principalPaid),paymentMoney.format(interestPaid)});
                // Decrement the values for the next payment
                loanBalance=loanBalance-principalPaid;
                interestPaid=loanBalance*(interestRate/100)/12;
                principalPaid=monthlyPayment-interestPaid;
            
            } // end for loop
        } // end showOutput

Similar Threads

  1. problems with JPanel and JFrame
    By v1nsai in forum New To Java
    Replies: 13
    Last Post: 04-08-2009, 08:49 PM
  2. Program using JPanel - problems
    By doozer8688 in forum New To Java
    Replies: 6
    Last Post: 11-05-2008, 12:16 AM
  3. JPanel / layout problems
    By Warhorsei in forum AWT / Swing
    Replies: 4
    Last Post: 06-04-2008, 06:26 AM
  4. Problems while loading a JPanel to JApplet...
    By Ananth Chellathurai in forum Java Applets
    Replies: 0
    Last Post: 11-24-2007, 11:47 AM
  5. JPanel Problems
    By Riftwalker in forum AWT / Swing
    Replies: 6
    Last Post: 10-16-2007, 12:16 AM

Posting Permissions

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