This discussion is archived
7 Replies Latest reply: Feb 23, 2009 7:53 PM by 843785 RSS

Having trouble understanding JTable

807599 Newbie
Currently Being Moderated
I've constructed a JTable to display output for a mortgage calculator. I know that in my actionPerformed method, I need to be able to pass calculated information out to my JTable for display. I believe I need to use a JTable.setValueAt(object, int, int).

What I seem to be missing from the various books/googles that I've done is exactly what are the object, int, int constructors? How do you set them up??? How do you pass your data into a row with three columns, then move on to the next row?
/*
     *******************************************************************************************
     Week 3:          Mortgage Calculator
     Programmer:     Christianne Dinsmore
     Date:          November 2006
     Filename:     Mortgage.java
     Purpose:     This program accepts input from a user for principal amount, term, and
     interest rate, and calculates the payment - as well as displaying an amortization table.
              This program allows users to enter new information, or exit the program.
     *******************************************************************************************
*/

import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import java.util.*;

class Mortgage extends Frame implements ActionListener
{
     public static final long serialVersionUID = 14865L;
     //Construct Panels
     JPanel inputPanel = new JPanel();
          JLabel prinAmtLabel = new JLabel("Principal Amount (US$):");
          JTextField prinAmtField = new JTextField(10);
          //add rateTerm strings and combo box
          String[] rateTermStrings = { "7 Years, 5.35% APR", "15 Years, 5.5% APR", "30 Years, 5.75% APR" };
          JComboBox rateTermList = new JComboBox(rateTermStrings);

     //Setup JTable to display Amortization
     TableModel dataModel = new AbstractTableModel()
     {
          private static final long serialVersionUID = 1L;
          public int getColumnCount() {return 3;}
          public int getRowCount() {return 360;}
          public Object getValueAt(int row, int col) {return new Integer(row*col);}
          //Set up column names and return them as column headers of JTable
          String[] columnNames = {"Payment Number", "Remaining Balance", "Interest Paid"};
          public String getColumnName(int col) { return columnNames[col].toString(); }
          public boolean isCellEditable(int rowIndex, int mColIndex) { return false; }
     };
     JTable outputTable = new JTable(dataModel);
     JScrollPane outputPane = new JScrollPane(outputTable);

     //Construct the button panel
     JPanel buttonPanel = new JPanel();
          JButton calcPmtButton = new JButton("Calculate Payment");
          JButton clearFieldsButton = new JButton("Clear Fields");
          JLabel paymentLabel = new JLabel("Your monthly payment will be:");
          JTextField paymentField = new JTextField(10);

     public Mortgage()
     {
          //Construct Layout
          this.setLayout(new BorderLayout());
               buttonPanel.setLayout(new FlowLayout());
               inputPanel.setLayout(new FlowLayout());

          //add components to button panel and button action listeners
          buttonPanel.add(calcPmtButton);
          calcPmtButton.addActionListener(this);
          calcPmtButton.setActionCommand("calc");
          buttonPanel.add(clearFieldsButton);
          clearFieldsButton.addActionListener(this);
          clearFieldsButton.setActionCommand("clear");
          buttonPanel.add(paymentLabel);
          buttonPanel.add(paymentField);
          //make the payment field non-editable
          paymentField.setEditable(false);

          //add componenets to input panel
          inputPanel.add(rateTermList);
          inputPanel.add(prinAmtLabel);
          inputPanel.add(prinAmtField);
          //Set index to start at 30 Year rate/term and Action Listener
          rateTermList.setSelectedIndex(2);
          rateTermList.addActionListener(this);

          //size the scroll pane
          outputPane.setPreferredSize(new Dimension(425, 150));

          //add panels to frame
          add(buttonPanel, BorderLayout.CENTER);
          add(inputPanel, BorderLayout.NORTH);
          add(outputPane, BorderLayout.SOUTH);

          //overriding the windowClosing() method will allow the user to click the (x) to exit the application
          addWindowListener(
                    new WindowAdapter()
                    {
                         public void windowClosing(WindowEvent e)
                         {
                              System.exit(0);
                         } //end windowClosing
                    }// end WindowAdapter
          );//end WindowListener

     }//end public mortgage

     public void actionPerformed(ActionEvent e)
     {
          if (e.getActionCommand().equals("calc"))
          {
               //Declare and initialize variables
               double prinAmt = 0;
               double interest = 0;
               double termYears = 0;
               double paymentMonthly = 0.00;

               //try and catch error control statements to gather input and test for validity
               try
               {
                    prinAmt = Double.valueOf(prinAmtField.getText()).doubleValue();
                    if (prinAmt <= 0)
                    {
                         JOptionPane.showMessageDialog(this, "Mortgage Amount Cannot be Less Than 0", "Error", JOptionPane.OK_OPTION);
                    }
               }
               catch (NumberFormatException ex)
               {
                    JOptionPane.showMessageDialog(this, "Please Enter a Valid Number for Principal Amount", "Error", JOptionPane.OK_OPTION);
                    return;
               }//end try/catch

               //set variables based on list choice
               String rateTermListChoice;
               rateTermListChoice = (String)rateTermList.getSelectedItem();
               int [] loanType = new int[] { 84, 180, 360 };
               //this is to hold the value of the array so we can pull the right payment number for the amortization table
               int i = 0;
               if (rateTermListChoice == "7 Years, 5.35% APR")
               {
                    interest = 5.35;
                    termYears = 7;
                    i = 0;

               }
               else if (rateTermListChoice == "15 Years, 5.5% APR")
               {
                    interest = 5.50;
                    termYears = 15;
                    i = 1;

               }
               else
                    interest = 5.75;
                    termYears = 30;
                    i = 2;

               //Format Results for Output in Currency
               NumberFormat USDollar = NumberFormat.getCurrencyInstance(Locale.US);

               //Equation to Calculate Payment
               //Sample Formula payment = [$100,000(1 + .00583)360 x .00583] / [(1 + .00583)360 - 1]
               //Calculate and Display Payment
               double interestMonthly = interest/1200;
               double termMonths = termYears * 12;
               double calc_1 = Math.pow(1 + interestMonthly, termMonths);
               paymentMonthly = ((prinAmt * calc_1) * interestMonthly)/(calc_1 - 1);
               String paymentMonthlyString = USDollar.format(paymentMonthly);
               paymentField.setText(paymentMonthlyString);

               //Begin Amortization Table
               int NumPayments=0;  //NumPayments holds the 0-360 Payment Number
               while (NumPayments<loanType)
                    {
                         //Equation to calculate the remaining loan balance of a fixed payment loan for a given number of months
                         //From www.mtgprofessor.com/formulas.htm
                         //**BalanceRemaining = PrincipalAmt[(1+InterestMonthly)^TermMonths - (1+InterestMonthly)^NumPayments]/[(1+InterestMonthly)^TermMonths -1]**
                         double calc_2 = Math.pow(1+ interestMonthly, NumPayments);
                         double BalanceRemaining = (prinAmt * (calc_1 - calc_2))/(calc_1 - 1);
                         if (NumPayments<loanType[i])
                         {
                              //Sent output to JTable
                              //1st send NumPayments to column1
                              //Then send BalanceRemaining to column2
                              //Last send InterestPaid (once I figure out what that is) to column3
                              //Go to next row
                              NumPayments++; //Increment NumPayments Variable
                              //Go back to loop to calculate

                         }
                         else
                         {
                              //Overset counter to exit loop (361 higher than all array values)
                              NumPayments=361;
                         }
                    } //end while
          }//end if
          else
          clearFields();
     }

     public void clearFields()
     {
          prinAmtField.setText("");
          paymentField.setText("");
          prinAmtField.requestFocus();
     }//end of clearFields() method

     public static void main(String args[])
     {
          //set frame properties
          Mortgage Jframe = new Mortgage();
          Jframe.setTitle("Dinsmore Mortgage Calculator v2.3");
          Jframe.setBounds(200,300,425,285);
          Jframe.setVisible(true);
          Jframe.setResizable(false);
     } //end of main
}//end of class Mortgage


Pointers, help, or most specifically - a tutorial link (can't find any that give me a good example of what I'm trying to do here) would be most helpful. My buddy told me to pass the data into an array somehow, then ppass the array to the JTable. Should I try that?