Results 1 to 5 of 5
  1. #1
    Laura Warren is offline Member
    Join Date
    Nov 2008
    Posts
    14
    Rep Power
    0

    Question JTable in Frame only shows 3 rows

    Hello:

    I have a series of panels in a frame, one of which contains a JTable. The table only displays 3 rows and I would like it to show more. Here's my code, (I know it's a mess - sorry). It's part of an assignment and needs to either allow the user to enter interest rate and term manually, or select interest rate and term from a combo box.

    I'm still working on the code for the manual entry portion, but can't figure why only three rows of the table display. My other problem is that I can't clear the values of the table when I "reset."

    Any help would be greatly appreciated. I'm fairly new at Java and struggling. My data validation is also a mess, but I'm more concerned with the table.

    Thanks, and the code is below.

    Laura


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import javax.swing.border.*;

    class WarrenMortgageAppWeek4
    {
    public static void main(String[] args)
    {
    JFrame Mortgageframe = new MortgageFrame();
    Mortgageframe.setVisible(true);
    }
    } //end of MortgageApp class


    class MortgageFrame extends JFrame
    {
    /* This section will set up the application window
    * and size it to fit the controls.
    *
    */

    public MortgageFrame()
    {
    setTitle("Laura Warren Mortgage Calculator (Week 4)");
    setSize(440, 520);
    centerWindow(this);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new MortgagePanel();
    this.add(panel);

    }

    private void centerWindow(Window w)
    {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    }
    }// end of MortgageFrame class

    // This section will specify the controls (labels, text fields, and buttons)
    // It will also declare variables and arrays

    class MortgagePanel extends JPanel implements ActionListener
    {
    private JLabel loanAmountLabel;
    private JRadioButton week2Style;
    private JRadioButton week3Style;
    private JTextField loanAmountTextField;
    private JLabel annualRateLabel;
    private JTextField annualRateTextField;
    private JLabel termLabel;
    private JTextField termTextField;
    private JLabel monthlyPaymentLabel;
    private JTextField monthlyPaymentTextField;
    private JLabel errorlbl;
    private JComboBox optionsCombo;
    private JTable paymentsTable;
    private DefaultTableModel table;
    private JButton calculateButton;
    private JButton resetButton;
    private JButton exitButton;
    private JScrollPane paymentsScrollPane;
    int rows = 400; //months not likely to exceed this value
    int columns = 4;
    String columnHeadings[] = { "Pmt #", "Beg Bal", "Principle", "Interest" };
    String[][]paymentData = new String[rows][columns];
    int[] TermYears = {7, 15, 30};
    double[] AnnualRate = {5.35, 5.5, 5.75};
    DecimalFormat PmtFormat = new DecimalFormat("$#,##0.00");

    public MortgagePanel()
    {
    //this section creates the top panel
    //holds the user input section for loan amount
    JPanel topPanel = new JPanel();
    topPanel.setLayout (new FlowLayout());
    loanAmountLabel = new JLabel("Amount of Loan: ");
    topPanel.add(loanAmountLabel);
    loanAmountTextField = new JTextField(10);
    topPanel.add(loanAmountTextField);

    //this section creates the area for the feedback label
    //messages appear in red
    JPanel errorPanel= new JPanel();
    errorPanel.setLayout (new FlowLayout());
    errorlbl = new JLabel(" ");
    errorlbl.setForeground (Color.red);
    errorPanel.add(errorlbl);

    //this section contains the option buttons

    Border loweredBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERE D);
    JPanel radioPanel = new JPanel();
    ButtonGroup StyleGroup = new ButtonGroup();
    radioPanel.setLayout (new FlowLayout(FlowLayout.LEFT));
    radioPanel.setBorder(BorderFactory.createTitledBor der(loweredBorder, "Style"));

    //week 2 style button
    week2Style = new JRadioButton("Week 2 Style: ");
    week2Style.addActionListener(this);
    StyleGroup.add(week2Style);
    radioPanel.add(week2Style);

    //week 3 style button
    week3Style = new JRadioButton("Week 3 Style: ");
    week3Style.addActionListener(this);
    StyleGroup.add(week3Style);
    radioPanel.add(week3Style);

    //week 2 style input panel
    JPanel weekTwoPanel = new JPanel();
    weekTwoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    annualRateLabel = new JLabel("Annual Interest Rate: ");
    weekTwoPanel.add(annualRateLabel);

    annualRateTextField = new JTextField(6);
    weekTwoPanel.add(annualRateTextField);

    termLabel = new JLabel("Term in Years: ");
    weekTwoPanel.add(termLabel);

    termTextField = new JTextField(4);
    weekTwoPanel.add(termTextField);



    //this section creates the area for the option box
    JPanel optionPanel = new JPanel();
    optionPanel.setLayout(new FlowLayout());
    String[]options = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
    optionsCombo = new JComboBox(options);
    optionPanel.add(optionsCombo);

    //this section contains the calculated monthly payment amount
    JPanel monthlyPaymentPanel = new JPanel();
    monthlyPaymentLabel = new JLabel("Monthly Payment:");
    monthlyPaymentPanel.add(monthlyPaymentLabel);
    monthlyPaymentTextField = new JTextField(10);
    monthlyPaymentTextField.setEditable(false);
    monthlyPaymentTextField.setFocusable(false);
    monthlyPaymentPanel.add(monthlyPaymentTextField);

    //this section contains settings for table listing
    paymentsTable = new JTable();
    table = new DefaultTableModel(columnHeadings,4);
    paymentsTable.setModel(table);
    paymentsTable.setPreferredScrollableViewportSize(n ew Dimension(500, 100));
    paymentsTable.setFillsViewportHeight(true);
    paymentsScrollPane = new JScrollPane(paymentsTable);



    //This section creates a panel to display the 3 buttons
    //(Calculate, Reset, and Exit)
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

    calculateButton = new JButton("Calculate");
    calculateButton.addActionListener(this);
    buttonPanel.add(calculateButton);

    resetButton = new JButton("Reset");
    resetButton.addActionListener(this);
    buttonPanel.add(resetButton);

    exitButton = new JButton("Exit");
    exitButton.addActionListener(this);
    buttonPanel.add(exitButton);

    //adds all sections to the main window using the GridLayout structure
    this.setLayout(new GridLayout(8,1));
    this.add(topPanel,BorderLayout.CENTER);
    this.add(radioPanel,BorderLayout.CENTER);
    this.add(errorPanel,BorderLayout.CENTER);
    this.add(weekTwoPanel, BorderLayout.CENTER);
    this.add(optionPanel,BorderLayout.CENTER);
    this.add(monthlyPaymentPanel,BorderLayout.CENTER);
    this.add(buttonPanel, BorderLayout.CENTER);
    this.add(paymentsScrollPane,BorderLayout.SOUTH);

    } //end of MortgagePanel class


    public void resetTable()
    {
    //clear existing values from table
    for(int paymentNumber=0; paymentNumber<=70; paymentNumber++)
    {
    paymentData[paymentNumber][0]=" ";
    paymentData[paymentNumber][1]=" ";
    paymentData[paymentNumber][2]=" ";
    paymentData[paymentNumber][3]=" ";
    }
    }
    /*
    This section defines what happens when each button is clicked.
    * The Exit button will close the application.
    * The Reset button will clear all fields.
    * The Calculate button will test for missing loan amount
    * When valid loan amount is entered, the monthly payment calculates.
    */
    public void actionPerformed(ActionEvent e) throws NumberFormatException
    {
    Object source = e.getSource();
    if (source == exitButton)
    System.exit(0);
    //================================================== ======

    if (source ==resetButton)
    {
    loanAmountTextField.setText("");
    monthlyPaymentTextField.setText("");
    errorlbl.setText(" ");
    resetTable();

    }//end if source reset
    //================================================== ======
    // Calculate button has been clicked
    if (source == calculateButton)
    {
    double monthlyPayment = 0.0;
    double interestRate = 0.0;
    int years = 0;


    //use rate and term values selected from combo box
    switch (optionsCombo.getSelectedIndex())
    {
    case 0:
    interestRate = 5.35;
    years = 7;
    break;
    case 1:
    interestRate = 5.5;
    years= 15;
    break;
    case 2:
    interestRate = 5.75;
    years = 30;
    break;
    } // end switch

    //----------Test for Loan Amount field
    try
    {
    double loanAmount = Double.parseDouble(loanAmountTextField.getText());
    errorlbl.setText("Thank you.");
    if (loanAmount <=0) throw new NumberFormatException();
    monthlyPayment = CalculatePayment(loanAmount, interestRate, years);
    }
    catch(NumberFormatException m)
    {
    errorlbl.setText("Please enter a valid loan amount.");
    resetTable();
    loanAmountTextField.requestFocus();
    }

    //format and place monthly payment calculation
    //call method to calculate values for Loan Amount
    //calculates table

    double loanAmount = Double.parseDouble(loanAmountTextField.getText());
    CalculatePayment(loanAmount,interestRate,years);
    monthlyPaymentTextField.setText(PmtFormat.format(m onthlyPayment));
    table.setDataVector(paymentData, columnHeadings);

    }// end of Calculate button events

    }// end of actionPerformed event


    public double CalculatePayment(double loanAmount, double interestRate, int years)
    {
    double monthlyPayment;
    //this section calculates the montly payment
    double monthlyRate = interestRate / 12 /100;
    int termMonths = years * 12;
    monthlyPayment = loanAmount * monthlyRate/(1-(1/Math.pow(1 + monthlyRate,termMonths)));


    //declare and initialize variable for amortization calculations
    double BeginningBal = Double.parseDouble(loanAmountTextField.getText());
    double EndingBal;
    double Principal;
    double InterestPaid;
    double CumInterest = 0;


    //this section loops through all payments and calculates
    //Beginning Balance, Principle, and Interest Paid values

    for (int MonthCounter = 1; MonthCounter <= termMonths; MonthCounter++ ) //list data for each month
    {

    InterestPaid = BeginningBal * monthlyRate;
    Principal = monthlyPayment - InterestPaid;
    EndingBal = BeginningBal - Principal;
    CumInterest = CumInterest + InterestPaid;

    //this section will fill in table values row by row until all payments calculated
    paymentData[MonthCounter][0] = ""+MonthCounter;
    paymentData[MonthCounter][1] = PmtFormat.format(BeginningBal);
    paymentData[MonthCounter][2] = PmtFormat.format(Principal);
    paymentData[MonthCounter][3] = PmtFormat.format(InterestPaid);

    //the Ending Balance for one month becomes the Beginning Balance for the next
    BeginningBal = EndingBal;
    } // end for


    return monthlyPayment;
    } // end Calculate Payment method

    }// end of MortgagePanel class
    Laura

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    I'm not familiar with JFrame or JPanel but GridLayout has a numColumns variable that can be set. Perhaps JPanel has something similar?

    Have you tried setting the rows maxHeight to something smaller? The frame could have just reached its max capacity.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Several quick notes:

    1. Do you know about Netbeans? It's an IDE from Sun that is free. It has a visual Swing designer, which creates the view code for you. I know you don't have time now, but that's a lot of code to do by hand...

    2. The JTable goes inside the JScrollPane. I assume you are already doing that. The JScrollPane preferredSize is very likely what is controlling how much of the JTable is visible.

    3. Model-View-Controller sounds like a lot of work, but it saves time, even on projects of this size. Again, I know this isn't the time, but it's something worth learning if you want to do Java beyond this class.

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

    Default

    You're adding your paymentsScrollPane into a JPanel that uses GridLayout, and when you do that, the layout manager will ignore the preferred size of the JScrollPane and the JTable it holds. Rather than a GridLayout here, why not add most of your widgets using a BoxLayout? That will allow for different sized components.

    I also advise you not use NetBeans code generation until your Swing abilities are stronger. Otherwise it will slow down your Swing education, not enhance it. And education is what is most important here.

    Edit: I've worked with your code a bit. Create a JPanel and then have it use the BoxLayout set along the PAGE_AXIS. Add all of your components from the topPanel down to the paymentsScrollPane to this JPanel. Then add this JPanel to your MortgagePanel and you should be all set.
    Last edited by Fubarable; 12-23-2008 at 03:09 AM.

  5. #5
    Laura Warren is offline Member
    Join Date
    Nov 2008
    Posts
    14
    Rep Power
    0

    Thumbs up BoxLayout Worked!!

    Thank you so much for the help! It worked perfectly.

    By the way, I am using NetBeans but have been instructed not to generate any automatic code. (Actually, I wasn't even aware that there was a visual Swing designer until the instructor commented on it.)

    I realized why the table wasn't resetting -- I hadn't included the table.setDataVector(paymentData, columnHeadings); in the reset table method.

    Now I'm just working on validating the entries.

    Thanks once again for your replies.
    Laura

Similar Threads

  1. Replies: 11
    Last Post: 08-19-2008, 12:29 PM
  2. Replies: 2
    Last Post: 05-15-2008, 11:15 AM
  3. Caling an Applet Method thru VBScript that shows a dailog box
    By prachi_goliwadekar in forum Java Applets
    Replies: 1
    Last Post: 04-18-2008, 07:45 AM
  4. Deleting All rows in the JTable
    By surot in forum New To Java
    Replies: 1
    Last Post: 04-16-2008, 11:44 AM
  5. display rows in jtable
    By osval in forum AWT / Swing
    Replies: 1
    Last Post: 08-06-2007, 09:54 PM

Posting Permissions

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