Link to home
Start Free TrialLog in
Avatar of craftyfirst
craftyfirstFlag for Afghanistan

asked on

Java Help with reading file and having certain items show and not show

Hi,

I'm trying to add to my Java application and I need it to read the file and it says it cannot find it and the other item I'm having an issue with is if one radio button is selected certain fields and text should show and when the other radio button is selected those items should disappear and the other fields and text that is associated with that radio button should show. InterestRate-Term.txt
// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;

// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

         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, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Get values from file Or");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Choose Values");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
            contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
            contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);

            
             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        contentPanel.removeAll();
                        contentPanel.add(principal_label);
                        contentPanel.add(principal_text);

                        contentPanel.add(rbutton01);
                        contentPanel.add(rbutton02);

                        contentPanel.add(years_label);
                        contentPanel.add(years_text);

                        contentPanel.add(rate_label);
                        contentPanel.add(rate_text);

                        contentPanel.add(btnCalculate);
                        contentPanel.add(btnReset);

                        setVisible(true);
                      }
                    }
             });

            rbutton01.setSelected(true);

            
            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                   contentPanel.removeAll();
                    contentPanel.add(principal_label);
                    contentPanel.add(principal_text);

                    contentPanel.add(rbutton01);
                    contentPanel.add(rbutton02);

                    contentPanel.add(choose_label);
                    contentPanel.add(choose_combo);

                    contentPanel.add(btnCalculate);
                    contentPanel.add(btnReset);

                    setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    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_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }

   
           

    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    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 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    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;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        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() {
                MortgageCalculator thisClass = new MortgageCalculator();
                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);

        }

    }
}

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image



Check this one. Works for me.

//package today042811;

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;



// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static 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, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Get values from file Or");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Choose Values");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
            contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
            contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

                    toReplace = new String[4];
            toReplace[0] =  "Select Mortgage";
            try{
            DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
                String buff = null;
                int count = 1;
                while((buff = in.readLine()) != null){
                    StringTokenizer t = new StringTokenizer(buff,",");
                    String perc = t.nextToken().trim();
                    String yrs = t.nextToken().trim();
                    toReplace[count] = yrs + " years at " + perc + "%";
                    count++;


                }
                  in.close();

            } catch(Exception ex){
                System.out.println(ex.toString());
                ex.printStackTrace();
            }


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        System.out.println("one button clicke");
                        contentPanel.removeAll();
                        contentPanel.add(principal_label);
                        contentPanel.add(principal_text);

                        contentPanel.add(rbutton01);
                        contentPanel.add(rbutton02);

                               choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.toReplace[jj]);

                   }
                        contentPanel.add(choose_label);
                          contentPanel.add(choose_combo);

                        contentPanel.add(years_label);
                        contentPanel.add(years_text);

                        contentPanel.add(rate_label);
                        contentPanel.add(rate_text);

                        contentPanel.add(btnCalculate);
                        contentPanel.add(btnReset);

                        setVisible(true);
                      }
                    }
             });

            rbutton02.setSelected(true);


            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                       System.out.println(" button two clicke");
                   contentPanel.removeAll();
                    contentPanel.add(principal_label);
                    contentPanel.add(principal_text);

                    contentPanel.add(rbutton01);
                    contentPanel.add(rbutton02);

                    choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.mortgage[jj]);
                   }

                    contentPanel.add(choose_label);
                    contentPanel.add(choose_combo);

                    contentPanel.add(btnCalculate);
                    contentPanel.add(btnReset);

                    setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    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_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    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 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    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;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        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() {
                MortgageCalculator thisClass = new MortgageCalculator();
                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);

        }

    }
}

Open in new window

Avatar of craftyfirst

ASKER

I replace my code with all of yours and it is still not working for me.

I'm still getting all the fields showing up and the fields that should be remove and appear when you click on the each of the radio buttons do not. And it is still not locating the text file.

I place the code here again that you gave me.

Thanks

//package today042811;

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;



// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static 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, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Get values from file Or");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Choose Values");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
            contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
            contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

                    toReplace = new String[4];
            toReplace[0] =  "Select Mortgage";
            try{
            DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
                String buff = null;
                int count = 1;
                while((buff = in.readLine()) != null){
                    StringTokenizer t = new StringTokenizer(buff,",");
                    String perc = t.nextToken().trim();
                    String yrs = t.nextToken().trim();
                    toReplace[count] = yrs + " years at " + perc + "%";
                    count++;


                }
                  in.close();

            } catch(Exception ex){
                System.out.println(ex.toString());
                ex.printStackTrace();
            }


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        System.out.println("one button clicke");
                        contentPanel.removeAll();
                        contentPanel.add(principal_label);
                        contentPanel.add(principal_text);

                        contentPanel.add(rbutton01);
                        contentPanel.add(rbutton02);

                               choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.toReplace[jj]);

                   }
                        contentPanel.add(choose_label);
                          contentPanel.add(choose_combo);

                        contentPanel.add(years_label);
                        contentPanel.add(years_text);

                        contentPanel.add(rate_label);
                        contentPanel.add(rate_text);

                        contentPanel.add(btnCalculate);
                        contentPanel.add(btnReset);

                        setVisible(true);
                      }
                    }
             });

            rbutton02.setSelected(true);


            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                       System.out.println(" button two clicke");
                   contentPanel.removeAll();
                    contentPanel.add(principal_label);
                    contentPanel.add(principal_text);

                    contentPanel.add(rbutton01);
                    contentPanel.add(rbutton02);

                    choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.mortgage[jj]);
                   }

                    contentPanel.add(choose_label);
                    contentPanel.add(choose_combo);

                    contentPanel.add(btnCalculate);
                    contentPanel.add(btnReset);

                    setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    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_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    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 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    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;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        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() {
                MortgageCalculator thisClass = new MortgageCalculator();
                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);

        }

    }
}

Open in new window


Did you change the contents of the file?
It was the same originally as in your mortgage[] array.
I changed in the file and saw the difference
User generated image User generated image InterestRate-Term.txt User generated image
I have uploaded a few images so you can see what I'm getting and what I want to happen.

screenshotpanel.jpg - this is what I get when I run the program. Fields are over lapping. All the elements are showing no which button you choose.

screenshotChooseValues.jpg - this is what the Frame should look like if radio button 02 is selected. Then the user can choose from the drop down and the field for the rate and years are not there. I had take out some code to show you and this actually works.

screenshotGetValuesFile.jpg - this is what the frame should look like if radio button 01 is selected. Then the user can enter rate and years and it should grap it from the text file.

If you are referring to the text file, I just did and it still does not find the file. Maybe I'm misunderstanding what you are saying. Could it also be because I'm working on the Mac.
So you mean it does not fineing the file - do you see exception and stack trace printed?
If you are working on Mac you should update the line  
 DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
or you should know what folder is considerd to be default for this program when it is running.

So first let me know do you seee the Exception thte it cannot find the file at the startup moment in Java cosole.
Do you seee java console at all?
Thiese are the first and most imporatnt questions

If you are using IDE and if you know what is the home folder of your project, then
you should put this file  InterestRate-Term.txt  in that home folder.
I think it should work this way by default with all IDE's and  on any operating system.

If this does not work we may try to play with explicit path to the file.
Hope I'm explaining this right.

The JFrame shows like the example (screenshotpanel.jpg) I uploaded earlier but what happens all the fields show up when you first run it and some of the fields (Years and Combo Box) are on top of each other. So you cannot even do anything. And not matter which radio button you select the same fields show.

The only reason I got it to work was I did not add the JCombo Box at all and enter the values and got the popup saying it could not find the file.

If the radio button 2 (screenshotChooseValues.jpg ) is the default the JComboBox should show with its label and not the fields for the year and rate or labels for them.

When the user clicks on the radio button 1(screenshotGetValuesFile.jpg ) the JComboBox should disappear and the years_label, years_text, rate_label, and rate_text components should show.
right now I have the file in the project folder.

NetBeansProjects/MortgageCalcualtor/src/InterestRate-Term.txt

this is also where my MortgageCalculator.java file is.

In general, making this on the fly changaeable elements within the frame - repalce comboboxes
with text fields dependning on what radio bautton you use - it sometimes is problematic -
is it some requirement which someone dictates you ?

My thought was that if I select one radio box then it will take
set of default values (to choose one of three) from the program; if I select another radiobox
it will take a deafult set of three variants (to chosse one of three) from the file
but I didn't understand that it should change layout.
If you cannot live with such idea (does someone formulate to you exactly
how you need to use the file, or it is your decision?)
the please, explain how you see it.
Without the file I understand that we have a default set
of three variants and we need to chose with combobox which of the three to claculate.

The file contains nit one variant, but three, so if
toghether with reading from the file you want to replace combobox with
say two textfields for intersest and for year -
so how would we use all three lines of the file, or should
we use just the top line.

Again, if it was your idea to change the components on the fly and you can change it, I'd suggest
that you adopt my suggestion wwith the same layout but diffferent default
values either from program or from the file (we'll deall with overlapping in this case, i'm sure we'll find
the reason for it and remove it).

If changing components on the fly is a requirement, then we can think of it,but please, explain, do you mean that you want to replace choice from three with the two textfileds representing only one variant depending
on whether we read from file or not. Very much hope you understand my questions, please
try to reply in these terms. I kind of already did a lot on this code - it is a pity to throw away it.





 
Normally Interest-Rates.txt file should not be in the source
folder - it should rather be in the top folder of the project - then
the program should read it without additional path prepended
Ok thanks I will change it there.

As for the other issue.

Last weeks assignment I needed to add a combo box so the user could select a mortgage rate and number of years and when clicking on the button it would calculate the mortgage rate.

This week I need to expand on last weeks assignment is:
 
Modify the program from week four and add the following additional features: Read the interest rates and term years (separated by a comma) from a sequential file (provided) and insert the values into the appropriate arrays.

So the way I read that was I needed to have the two options. One where it would get the information from the text file or the other one where you could choose the combo box.

Unless I misunderstanding and need to get a better explanation from my  teacher.

I will be offline for about 2 hours since I will be on train commuting home. Will be back online later.
Hope what I explain makes sense. I will try and get more clairification from my teacher.
Avatar of Mick Barry
try this:

BufferedReader in = new BuffereredReader(new InputStreamReader(getClass().getResourcesAsStream("/InterestRate-Term.txt")));
String line = null;
while (null!=(line = in.readLine())) {
   String[] tokens = line.split(",");
   double rate = Double.parseDouble(tokens[0]);
   int term = Integer.parseInt(tokens[1]);
   // store these somewhere
}
in.close();
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

I think even my understanding is beyond what they required from you:

Modify the program from week four and add the following additional features: Read the interest rates and term years (separated by a comma) from a sequential file (provided) and insert the values into the appropriate arrays.

What that means tha instead of having ptions encoded into the program hard way they
wanted you to read these option form  file, it; s like you read configuration file from where you
read available choices.

That is excatly what the code I sent you does In addition
it has tow radioboxes which allow to choose whether we use hard ebncoded choices or we rathe offer choices
which weerre read fromn the file. these radioboxs are aready beyond what they required,
and frankly more logicla to be without tthem. But once we have them it sonly shows you know
how to use radioboxes.
So I suggest, let's clean up overlapping and ctick to this varaiant - we have some options encoded in the program
and alternative options are read from the file; depending on chosen radiobox
we use either one set or anther for the choice.

Let me know if you agree with that, and I'll look at the overlap issue, and then we'd only need to figure out where to put file
correctly in your environment, as for mr it reads file OK. So let me know.




"Modify the program from week four and add the following additional features: Read the interest rates and term years (separated by a comma) from a sequential file (provided) and insert the values into the appropriate arrays. " - this does not
speak at all about any changes in the GUI.
So waht we did fullt staisfies this and even doing something more.

So try to replace this one line
 DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
with what objects proposed:
BufferedReader in = new BuffereredReader(new InputStreamReader(getClass().getResourcesAsStream("/InterestRate-Term.txt")));
thouigh I still believe that your file needs to be not with the sources
but rather in the same folder wher you have classes.
But anyway try both ways, and let us know.
If the file is read - you'll reach the same stage as I see it
(change the lines in file so you can understand whether data are coming from program
or from file);
Then I'll look at overlapping - I'm sure it would not be difficult to resolve.





Ok. I will most likely will not be able to try this until tomorrow morning and will let you know if it works. I'm in transit right now and do not have access to computer.

Thanks for the help.

I also trying to get clarification and see if I do not have to have the combo box and only read from the file.
try the code I posted above, it should read your file for you
no need to move the file either, its fine where it is
> I also trying to get clarification and see if I do not have to have the combo box and only read from the file.

you still need the combo box.
just populate it with the values reda from the file using the code I postyed above

let me know if you need help getting it working
By no means any rush.

But I'm not suggestying not to have combo box -  we'll certainlt have combo box.
What your assignment suggests is to add the ability to populate this combo box not with hard-coded
array of data, but rather with the data which is read from the file.

we did that, and in addition even added radioboxes which can switch us between the hardcoded
array and the array raed from file (actually file is read from the beginning, and
radioboxes affect which of the two sets of data populates combobox).
 This is something extra - which you cannot read in your requirement,
but once you (and a little bit me also) went through pains of adding this radioboxes, sure let's keep them.


OK, this does not have any overlaps.

I attach two pictures where it shows dropdowns
in case values form file and values form array
are checked - the difference is that I made first two lines identical in the
file.


package today042811;

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;



// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static 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, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Values from file");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Values from array");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);
            rbutton02.setSelected(true);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
       //     contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
       //     contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
        //    contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
       //     contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

                    toReplace = new String[4];
            toReplace[0] =  "Select Mortgage";
            try{
            DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
                String buff = null;
                int count = 1;
                while((buff = in.readLine()) != null){
                    StringTokenizer t = new StringTokenizer(buff,",");
                    String perc = t.nextToken().trim();
                    String yrs = t.nextToken().trim();
                    toReplace[count] = yrs + " years at " + perc + "%";
                    count++;


                }
                  in.close();

            } catch(Exception ex){
                System.out.println(ex.toString());
                ex.printStackTrace();
            }


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        System.out.println("one button clicke");
                      //  contentPanel.removeAll();
                      //  contentPanel.add(principal_label);
                      //  contentPanel.add(principal_text);

                      //  contentPanel.add(rbutton01);
                      //  contentPanel.add(rbutton02);

                               choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.toReplace[jj]);

                   }
                        contentPanel.add(choose_label);
                          contentPanel.add(choose_combo);

                   //     contentPanel.add(years_label);
                   //     contentPanel.add(years_text);

                  //      contentPanel.add(rate_label);
                 //       contentPanel.add(rate_text);

                      //  contentPanel.add(btnCalculate);
                      //  contentPanel.add(btnReset);

                      //  setVisible(true);
                      }
                    }
             });

           // rbutton02.setSelected(true);


            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                       System.out.println(" button two clicke");
                 //  contentPanel.removeAll();
                 //   contentPanel.add(principal_label);
                 //   contentPanel.add(principal_text);

                   // contentPanel.add(rbutton01);
                   // contentPanel.add(rbutton02);

                    choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.mortgage[jj]);
                   }

                  //  contentPanel.add(choose_label);
                  //  contentPanel.add(choose_combo);

                  //  contentPanel.add(btnCalculate);
                  //  contentPanel.add(btnReset);

                  //  setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                      /*
                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                */
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    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_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    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 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    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;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        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() {
                MortgageCalculator thisClass = new MortgageCalculator();
                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);

        }

    }
}

Open in new window

valuesFromArray.PNG
valuesFromFile.PNG
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks this works now.
Great! You are always welcome.