Link to home
Start Free TrialLog in
Avatar of zomrob
zomrob

asked on

reading from a file

I did week 4 assignment and did fine. Now week 5. I have to read the interest from a file, which I have created as data.txt ( this how it is in the file 0,.0535,.055,.0575. Ok so can I have the combo box read from the file when the user selects the amount. In my mind this seems to be the easiest way. I have tried several read from file examples with not luck.



 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MortgageGUI2;

/**
 *
 * @author robertwalters
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

  // package MortgageGUI2;

   /**
*
* @author robertwalters
*/

   import java.awt.*;
   import java.awt.Color.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.lang.Math.*;
   import java.text.DecimalFormat;         //Import for decimal points
   import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;





   public class MortgageGUI2a extends JFrame  {
       static String sep = System.getProperty("line.separator");
    double MortgageAmount = 0;                    //Variable Mortgage
   double  LoanTerm  = 0.0;
   double loanmonths= 0.0;//Number of Months
   double [] InterestRate = {.0535,.055,.0575};                      //Interest Rate for Loan
    double monthlyInterest = 0;
   int[] years = {1,7,15,30};
   int  months = 0;
    double monthlyPayment = 0.00;
   double loanBalance = 0;
    double currentMonthInterest = 0.00 ;
   double currentMonthPrinciple = 0.00;
   int counter = 0;
   int paymentCounter = 0;
   int breakCounter = 0;
    double userInterest = 0.0;
   double princPayment = 0;
   double remainMortgage=0;
       String s3value;
        String s1value;
        String s2value;
   DecimalFormat eachpayment = new DecimalFormat ("$###,##0.00");






     public MortgageGUI2a(){
        setLayout(new GridBagLayout());

        GridBagConstraints c= new GridBagConstraints();
         label1 = new JLabel("Mortgage Amount");                   //Mortgage label
         c.fill= GridBagConstraints.HORIZONTAL;
         c.gridx=0;
         c.gridy=0;
         add(label1,c);

         textfield1=new JTextField(15);                         //Mortgage Text
             c.fill=GridBagConstraints.HORIZONTAL;
            c.gridx=5;
            c.gridy=0;
            c.gridwidth=3;
             add (textfield1,c);


          label2=new JLabel("Interest Rate");                        //Interest label
           c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=2;
             c.gridwidth=1;
            add(label2,c);

            combo2 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=2;
            c.gridwidth=1;
            add(combo2,c);
            combo2.setEditable(true) ;
            combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Enter Rate below "," ", }));
                    combo2.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo2.getSelectedItem();
        textfield2.setText(str);
           s1value = str;
                        }

   });
        textfield2=new JTextField(15);                              //Interest Text
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=5;
             c.gridy=2;
             c.gridwidth=3;
             add (textfield2,c);
             textfield2.setEditable(false);
// textfield 2

        label3=new JLabel("Loan Term (Years)");                    //Number of Months Financed
          c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=3;
             c.gridwidth=1;
            add(label3,c);

             combo3 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=3;
            c.gridwidth=1;
            add(combo3,c);
            combo3.setEditable(false) ;
            combo3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {" ","7","15","30" }));
                    combo3.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo3.getSelectedItem();
        textfield3.setText(str);
          s2value = str;

                        }

   });
        textfield3=new JTextField(15);                            // Loan Months
          c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=3;
             c.gridwidth=3;
            add (textfield3,c);
            textfield3.setEditable(false);
//textfield 3

             label4=new JLabel("Loan Term (Years)");                    //Number of Months Financed
              c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=4;
             c.gridwidth=1;
            add(label4,c);
            combo4 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=4;
            c.gridwidth=1;
            add(combo4,c);
             combo4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "?","7years at 5.35","15years at 5.5","30 years at 5.75" }));
                    combo4.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo4.getSelectedItem();
        textfield4.setText(str);
         System.out.println("str: " + str);
         s3value = str;
                        }

   });
            textfield4=new JTextField(15);                            // Loan Months
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=4;
             c.gridwidth=3;
            add (textfield4,c);
            textfield4.setEditable(false);
         
        label5=new JLabel("Payment");                                // Payment label
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=5;
             c.gridwidth=1;
            add(label5,c);


       textfield5=new JTextField(15);                               // Calculation Result
         c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=6;
             c.gridy=5;
             c.gridwidth=3;
             add (textfield5,c);
              textfield5.setEditable(false);



        Jbutton1=new JButton("Calculate");                          // Calculate Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=9;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton1,c);

        Jbutton1.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton1.addActionListener(new ActionListener() {            // Calculate Button Function

            public void itemStateChanged(ItemEvent event) {

  Object select = event.getItem();

              String selection = select.toString();
}
               public void actionPerformed(ActionEvent e) {

   if (e.getSource() == Jbutton1)

           {
              MortgageAmount = Double.parseDouble(textfield1.getText());
               //String s1 =    textfield2.getText().trim();
               String s1 = s1value;
                           System.out.println("s1 " + s1);
                 //String s2 =    textfield3.getText().trim();
                   String s2 = s2value;
                        System.out.println("s2 " + s1);



               if(s1==null || s1.equals("?")){
                  // String s3 =   textfield4.getText().trim();
                   String s3 = s3value;
                     System.out.println("s3 " + s3);
                    s1 = s3.substring(s3.indexOf("at")+2).trim();
                   System.out.println("s1 " + s1);
                     s2 = s3.substring(0,s3.indexOf("year")).trim();
                     System.out.println("s2 " + s2);

               }

             // userInterest = Double.parseDouble (textfield2.getText());
              //LoanTerm = Double.parseDouble (textfield3.getText());

               System.out.println("  s1 before " + s1);
                System.out.println("  s2 before " + s2);

               userInterest = Double.parseDouble (s1);
              LoanTerm = Double.parseDouble (s2);

			   CalculateMonthlyPayment() ;

               textfield5.setText(eachpayment.format(monthlyPayment));


			   repaint();
			   loanmonths = LoanTerm * 12;
			   loanBalance = MortgageAmount;

               String totalString = "";

              for (months = 1; months <= loanmonths; months++)
              {

                  //monthly interest calculation

                  monthlyInterest = userInterest / (1200.00);

                  //current months interest amount calculation

                  currentMonthInterest = loanBalance * monthlyInterest;

                  //current months principale amount calculation

                  currentMonthPrinciple = monthlyPayment - currentMonthInterest;

                  //current months interest minus loan amount
                 //provides new principle amount
                 loanBalance = loanBalance - currentMonthPrinciple;

                        totalString +=   "   Payment    " + months +   "           Monthly Payment    " + eachpayment.format(monthlyPayment)+
                                 "         Monthly Principle    " + eachpayment.format(currentMonthPrinciple)
                             +   "                Monthly Interest    " + eachpayment.format(currentMonthInterest)
                             +   "                    Loan Balance   "
                             + eachpayment.format(loanBalance) +   "\n";
        }
                      txtSubmitterComment.setText(totalString);
                    textfield4.setText(s3value);
                    textfield4.setForeground(Color.black);

                    }
            }




        });



        Jbutton2=new JButton("Clear");                             // Clear Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=6;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton2,c);





         txtSubmitterComment = new JTextArea(20,4);
         txtSubmitterComment.setLineWrap(false);
         txtSubmitterComment.setWrapStyleWord(false);
        // if(currentRecord.getSubmitter_comment() != null)
         txtSubmitterComment.setText("");
         paneForSubmitterComment = new JScrollPane(txtSubmitterComment);
           c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=20;
          add( paneForSubmitterComment,c);



          monthArea = new MyTextArea(200,200);

         String s = "test" + sep + "test1";
         monthArea.setText(s);


       scroll = new JScrollPane(monthArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            myPanel = new JPanel();
            myPanel.setPreferredSize(new Dimension(200,200));
             myPanel.setLayout(new BorderLayout());
                myPanel.add(scroll,BorderLayout.CENTER);

         JScrollPane pane = new JScrollPane();
            pane.setSize(100,100);
            pane.add(monthArea);
            c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=150;
             add(myPanel,c);
              scroll.revalidate();




         monthText = new JTextField[12];
            for (int jj=0; jj<monthText.length; jj++){
                monthText[jj] = new JTextField(70);
                 c.fill= GridBagConstraints.HORIZONTAL;
                  c.gridx=0;
             c.gridy=25 + 5*jj;
              c.gridwidth=20;
              c.gridheight=5;
             add (monthText[jj],c);
            }





        Jbutton2.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton2.addActionListener(new ActionListener() {             //Clear Button Function
               public void actionPerformed(ActionEvent e) {
                combo3.setSelectedIndex(0);
                combo2.setSelectedIndex(0);
                combo4.setSelectedIndex(0);
                textfield1.setText("");
                textfield2.setText("");
                textfield3.setText("");
                textfield4.setText("");
                textfield5.setText("");

                   txtSubmitterComment.setText("");
                     for (int jj=0; jj<monthText.length; jj++){
                         monthText[jj].setText("");
                     }
                paymentCounter = 0;



              // TODO add your handling code here:;
             }

        });


         Jbutton3=new JButton("Exit");                                  //Exit Button
           c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=0;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton3,c);

        Jbutton3.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton3.addActionListener(new ActionListener() {               //Exit Button Function
               public void actionPerformed(ActionEvent e) {
                   System.exit(0);
            }
        });


         event evt = new event();
        Jbutton1.addActionListener(evt);
        Jbutton2.addActionListener(evt);
        Jbutton3.addActionListener(evt);
   }
    double CalculateMonthlyPayment()       {

        String s1 =    textfield2.getText().trim();
                       System.out.println("s1 " + s1);
             String s2 =    textfield3.getText().trim();
                    System.out.println("s2 " + s1);

           if(s1==null || s1.equals("")){
              // String s3 =   textfield4.getText().trim();
               String s3 = s3value;
                 System.out.println("s3 " + s3);
                s1 = s3.substring(s3.indexOf("at")+2).trim();
               System.out.println("s1 " + s1);
                 s2 = s3.substring(0,s3.indexOf("year")).trim();
                 System.out.println("s2 " + s2);

           }


        //Parse text to Float Type
       MortgageAmount=Float.parseFloat(textfield1.getText());

         LoanTerm=Float.parseFloat(s2);
       monthlyInterest=Float.parseFloat(s1);

      //LoanTerm=Float.parseFloat(textfield3.getText());
       //monthlyInterest=Float.parseFloat(textfield2.getText());





       paymentCounter += counter + 1;

           return monthlyPayment = ((MortgageAmount * monthlyInterest / 100 / 12) / (1 - Math.pow(1 + monthlyInterest / 100 / 12, - LoanTerm *12)));



   }
   {

   }
     public class event implements ActionListener {
        public void actionPerformed(ActionEvent evt ) {




  



        }





   }


   public static void main (String args[]){                                  //GUI Frame
       MortgageGUI2a gui= new MortgageGUI2a();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(900,900);
        gui.setVisible(true);
       gui.setTitle("Mortgage Calculator");


    }
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JButton JButton4;
    JButton Jbutton1;
    JButton Jbutton2;
    JButton Jbutton3;
    JTextField textfield1;
    JTextField textfield2;
    JTextField textfield3;
    JTextField textfield4;
    JTextField textfield5;
    JComboBox combo2;
    JComboBox combo3;
    JComboBox combo4;
    JTextField[] monthText;
    MyTextArea monthArea;
    JPanel myPanel;
    JScrollPane scroll;
    JTextArea txtSubmitterComment;
    JScrollPane paneForSubmitterComment;





    }

class MyTextArea extends JTextArea{

    public MyTextArea(int x, int y){
        super(x,y);
    }
    public Dimension setPreferredSize(){
        Dimension d = new Dimension (200,200);
        return d;

    }
}

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

This should read from a file rates.txt in c:\temp\test folder

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MortgageGUI2;

/**
 *
 * @author robertwalters
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

  // package MortgageGUI2;

   /**
*
* @author robertwalters
*/

   import java.awt.*;
   import java.awt.Color.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.lang.Math.*;
   import java.text.DecimalFormat;         //Import for decimal points
   import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
   import java.io.DataInputStream;
   import java.io.FileInputStream;
   import java.util.StringTokenizer;
   import java.util.ArrayList;


 public class MortgageGUI2a extends JFrame  {
       static String sep = System.getProperty("line.separator");
    double MortgageAmount = 0;                    //Variable Mortgage
   double  LoanTerm  = 0.0;
   double loanmonths= 0.0;//Number of Months
   double [] InterestRate = {.0535,.055,.0575};                      //Interest Rate for Loan
    double monthlyInterest = 0;
   int[] years = {1,7,15,30};
   int  months = 0;
    double monthlyPayment = 0.00;
   double loanBalance = 0;
    double currentMonthInterest = 0.00 ;
   double currentMonthPrinciple = 0.00;
   int counter = 0;
   int paymentCounter = 0;
   int breakCounter = 0;
    double userInterest = 0.0;
   double princPayment = 0;
   double remainMortgage=0;
       String s3value;
        String s1value;
        String s2value;
   DecimalFormat eachpayment = new DecimalFormat ("$###,##0.00");






     public MortgageGUI2a(){
        setLayout(new GridBagLayout());

        GridBagConstraints c= new GridBagConstraints();
         label1 = new JLabel("Mortgage Amount");                   //Mortgage label
         c.fill= GridBagConstraints.HORIZONTAL;
         c.gridx=0;
         c.gridy=0;
         add(label1,c);

         textfield1=new JTextField(15);                         //Mortgage Text
             c.fill=GridBagConstraints.HORIZONTAL;
            c.gridx=5;
            c.gridy=0;
            c.gridwidth=3;
             add (textfield1,c);


          label2=new JLabel("Interest Rate");                        //Interest label
           c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=2;
             c.gridwidth=1;
            add(label2,c);

            combo2 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=2;
            c.gridwidth=1;
            add(combo2,c);
            combo2.setEditable(true) ;

         ArrayList aa = new ArrayList();
         aa.add("Enter rate below");

         try{

         DataInputStream in = new DataInputStream(new FileInputStream("C:\\temp\\test\\rates.txt"));
             String buff = in.readLine();
             StringTokenizer t = new StringTokenizer(buff, " ,");
                while(t.hasMoreTokens())aa.add(t.nextToken());
             in.close();


         }
         catch(Exception ex){
             System.out.println("Error " + ex.toString());
             ex.printStackTrace();
         }
          String [] rates = new String[aa.size()];
         for(int j=0; j<aa.size(); j++){
                   rates[j] = (String) aa.get(j);
         }

            //combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Enter Rate below "," ", }));
           combo2.setModel(new javax.swing.DefaultComboBoxModel(rates));
                    combo2.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo2.getSelectedItem();
        textfield2.setText(str);
           s1value = str;
                        }

   });
        textfield2=new JTextField(15);                              //Interest Text
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=5;
             c.gridy=2;
             c.gridwidth=3;
             add (textfield2,c);
             textfield2.setEditable(false);
// textfield 2

        label3=new JLabel("Loan Term (Years)");                    //Number of Months Financed
          c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=3;
             c.gridwidth=1;
            add(label3,c);

             combo3 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=3;
            c.gridwidth=1;
            add(combo3,c);
            combo3.setEditable(false) ;
            combo3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {" ","7","15","30" }));
                    combo3.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo3.getSelectedItem();
        textfield3.setText(str);
          s2value = str;

                        }

   });
        textfield3=new JTextField(15);                            // Loan Months
          c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=3;
             c.gridwidth=3;
            add (textfield3,c);
            textfield3.setEditable(false);
//textfield 3

             label4=new JLabel("Loan Term (Years)");                    //Number of Months Financed
              c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=4;
             c.gridwidth=1;
            add(label4,c);
            combo4 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=4;
            c.gridwidth=1;
            add(combo4,c);
             combo4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "?","7years at 5.35","15years at 5.5","30 years at 5.75" }));
                    combo4.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo4.getSelectedItem();
        textfield4.setText(str);
         System.out.println("str: " + str);
         s3value = str;
                        }

   });
            textfield4=new JTextField(15);                            // Loan Months
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=4;
             c.gridwidth=3;
            add (textfield4,c);
            textfield4.setEditable(false);

        label5=new JLabel("Payment");                                // Payment label
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=5;
             c.gridwidth=1;
            add(label5,c);


       textfield5=new JTextField(15);                               // Calculation Result
         c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=6;
             c.gridy=5;
             c.gridwidth=3;
             add (textfield5,c);
              textfield5.setEditable(false);



        Jbutton1=new JButton("Calculate");                          // Calculate Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=9;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton1,c);

        Jbutton1.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton1.addActionListener(new ActionListener() {            // Calculate Button Function

            public void itemStateChanged(ItemEvent event) {

  Object select = event.getItem();

              String selection = select.toString();
}
               public void actionPerformed(ActionEvent e) {

   if (e.getSource() == Jbutton1)

           {
              MortgageAmount = Double.parseDouble(textfield1.getText());
               //String s1 =    textfield2.getText().trim();
               String s1 = s1value;
                           System.out.println("s1 " + s1);
                 //String s2 =    textfield3.getText().trim();
                   String s2 = s2value;
                        System.out.println("s2 " + s1);



               if(s1==null || s1.equals("?")){
                  // String s3 =   textfield4.getText().trim();
                   String s3 = s3value;
                     System.out.println("s3 " + s3);
                    s1 = s3.substring(s3.indexOf("at")+2).trim();
                   System.out.println("s1 " + s1);
                     s2 = s3.substring(0,s3.indexOf("year")).trim();
                     System.out.println("s2 " + s2);

               }

             // userInterest = Double.parseDouble (textfield2.getText());
              //LoanTerm = Double.parseDouble (textfield3.getText());

               System.out.println("  s1 before " + s1);
                System.out.println("  s2 before " + s2);

               userInterest = Double.parseDouble (s1);
              LoanTerm = Double.parseDouble (s2);

			   CalculateMonthlyPayment() ;

               textfield5.setText(eachpayment.format(monthlyPayment));


			   repaint();
			   loanmonths = LoanTerm * 12;
			   loanBalance = MortgageAmount;

               String totalString = "";

              for (months = 1; months <= loanmonths; months++)
              {

                  //monthly interest calculation

                  monthlyInterest = userInterest / (1200.00);

                  //current months interest amount calculation

                  currentMonthInterest = loanBalance * monthlyInterest;

                  //current months principale amount calculation

                  currentMonthPrinciple = monthlyPayment - currentMonthInterest;

                  //current months interest minus loan amount
                 //provides new principle amount
                 loanBalance = loanBalance - currentMonthPrinciple;

                        totalString +=   "   Payment    " + months +   "           Monthly Payment    " + eachpayment.format(monthlyPayment)+
                                 "         Monthly Principle    " + eachpayment.format(currentMonthPrinciple)
                             +   "                Monthly Interest    " + eachpayment.format(currentMonthInterest)
                             +   "                    Loan Balance   "
                             + eachpayment.format(loanBalance) +   "\n";
        }
                      txtSubmitterComment.setText(totalString);
                    textfield4.setText(s3value);
                    textfield4.setForeground(Color.black);

                    }
            }




        });



        Jbutton2=new JButton("Clear");                             // Clear Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=6;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton2,c);





         txtSubmitterComment = new JTextArea(20,4);
         txtSubmitterComment.setLineWrap(false);
         txtSubmitterComment.setWrapStyleWord(false);
        // if(currentRecord.getSubmitter_comment() != null)
         txtSubmitterComment.setText("");
         paneForSubmitterComment = new JScrollPane(txtSubmitterComment);
           c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=20;
          add( paneForSubmitterComment,c);



          monthArea = new MyTextArea(200,200);

         String s = "test" + sep + "test1";
         monthArea.setText(s);


       scroll = new JScrollPane(monthArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            myPanel = new JPanel();
            myPanel.setPreferredSize(new Dimension(200,200));
             myPanel.setLayout(new BorderLayout());
                myPanel.add(scroll,BorderLayout.CENTER);

         JScrollPane pane = new JScrollPane();
            pane.setSize(100,100);
            pane.add(monthArea);
            c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=150;
             add(myPanel,c);
              scroll.revalidate();




         monthText = new JTextField[12];
            for (int jj=0; jj<monthText.length; jj++){
                monthText[jj] = new JTextField(70);
                 c.fill= GridBagConstraints.HORIZONTAL;
                  c.gridx=0;
             c.gridy=25 + 5*jj;
              c.gridwidth=20;
              c.gridheight=5;
             add (monthText[jj],c);
            }





        Jbutton2.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton2.addActionListener(new ActionListener() {             //Clear Button Function
               public void actionPerformed(ActionEvent e) {
                combo3.setSelectedIndex(0);
                combo2.setSelectedIndex(0);
                combo4.setSelectedIndex(0);
                textfield1.setText("");
                textfield2.setText("");
                textfield3.setText("");
                textfield4.setText("");
                textfield5.setText("");

                   txtSubmitterComment.setText("");
                     for (int jj=0; jj<monthText.length; jj++){
                         monthText[jj].setText("");
                     }
                paymentCounter = 0;



              // TODO add your handling code here:;
             }

        });


         Jbutton3=new JButton("Exit");                                  //Exit Button
           c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=0;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton3,c);

        Jbutton3.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton3.addActionListener(new ActionListener() {               //Exit Button Function
               public void actionPerformed(ActionEvent e) {
                   System.exit(0);
            }
        });


         event evt = new event();
        Jbutton1.addActionListener(evt);
        Jbutton2.addActionListener(evt);
        Jbutton3.addActionListener(evt);
   }
    double CalculateMonthlyPayment()       {

        String s1 =    textfield2.getText().trim();
                       System.out.println("s1 " + s1);
             String s2 =    textfield3.getText().trim();
                    System.out.println("s2 " + s1);

           if(s1==null || s1.equals("")){
              // String s3 =   textfield4.getText().trim();
               String s3 = s3value;
                 System.out.println("s3 " + s3);
                s1 = s3.substring(s3.indexOf("at")+2).trim();
               System.out.println("s1 " + s1);
                 s2 = s3.substring(0,s3.indexOf("year")).trim();
                 System.out.println("s2 " + s2);

           }


        //Parse text to Float Type
       MortgageAmount=Float.parseFloat(textfield1.getText());

         LoanTerm=Float.parseFloat(s2);
       monthlyInterest=Float.parseFloat(s1);

      //LoanTerm=Float.parseFloat(textfield3.getText());
       //monthlyInterest=Float.parseFloat(textfield2.getText());





       paymentCounter += counter + 1;

           return monthlyPayment = ((MortgageAmount * monthlyInterest / 100 / 12) / (1 - Math.pow(1 + monthlyInterest / 100 / 12, - LoanTerm *12)));



   }
   {

   }
     public class event implements ActionListener {
        public void actionPerformed(ActionEvent evt ) {








        }





   }


   public static void main (String args[]){                                  //GUI Frame
       MortgageGUI2a gui= new MortgageGUI2a();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(900,900);
        gui.setVisible(true);
       gui.setTitle("Mortgage Calculator");


    }
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JButton JButton4;
    JButton Jbutton1;
    JButton Jbutton2;
    JButton Jbutton3;
    JTextField textfield1;
    JTextField textfield2;
    JTextField textfield3;
    JTextField textfield4;
    JTextField textfield5;
    JComboBox combo2;
    JComboBox combo3;
    JComboBox combo4;
    JTextField[] monthText;
    MyTextArea monthArea;
    JPanel myPanel;
    JScrollPane scroll;
    JTextArea txtSubmitterComment;
    JScrollPane paneForSubmitterComment;





    }

class MyTextArea extends JTextArea{

    public MyTextArea(int x, int y){
        super(x,y);
    }
    public Dimension setPreferredSize(){
        Dimension d = new Dimension (200,200);
        return d;

    }
}

Open in new window

rates.txt
Avatar of zomrob
zomrob

ASKER

Awesome, and I actually had a similiar code but could not figure out where to run it. I was adding it at the end of the combo2 code. I did not have it the same but I do understand what the code is doing. I know it works because when I made the folder I named it wrong and had several errors, but I have them fixed.

Ok I have downloaded a program called JFreeChart, because I have to supposedly make a chart for this too. Is the chart something that will run seperatly from this program. I mean would I build the chart and have it reference this program or build it inside this one. I am watching the JFreeChart tutorial now. Again thanks for your help.
I guess, when youvdo calculation you should pop-up the new window - create JFrame, and place inside of it the some comoponent from JfreeChart and feed calculared numbers into it, so that it shows the chart. Try todo  it this way - we'll then help youi if you see problems
Avatar of Mick Barry
Avatar of zomrob

ASKER

OK well I thought I had something but we are not allowed to use JFreeChart so. What I have attached is a file called piechart. I added a JButton(Chart) to my program to call the pie chart.
My idea was to have the pie chart called from a file when the JButton is clicked.
I can not get that to happen. Is there an easier way to do this or am I on the right track.

Below is what I have but there are several errors at the calling point. I tried to do it the same as the first time with no avail.








 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MortgageGUI2;

/**
 *
 * @author robertwalters
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

  // package MortgageGUI2;

   /**
*
* @author robertwalters
*/

   import java.awt.*;
   import java.awt.Color.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.lang.Math.*;
   import java.text.DecimalFormat;         //Import for decimal points
   import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
   import java.io.DataInputStream;
   import java.io.FileInputStream;
   import java.util.StringTokenizer;
   import java.util.ArrayList;


 public class MortgageGUI2a extends JFrame  {
       static String sep = System.getProperty("line.separator");
    double MortgageAmount = 0;                    //Variable Mortgage
   double  LoanTerm  = 0.0;
   double loanmonths= 0.0;//Number of Months
   double [] InterestRate = {.0535,.055,.0575};                      //Interest Rate for Loan
    double monthlyInterest = 0;
   int[] years = {1,7,15,30};
   int  months = 0;
    double monthlyPayment = 0.00;
   double loanBalance = 0;
    double currentMonthInterest = 0.00 ;
   double currentMonthPrinciple = 0.00;
   int counter = 0;
   int paymentCounter = 0;
   int breakCounter = 0;
    double userInterest = 0.0;
   double princPayment = 0;
   double remainMortgage=0;
       String s3value;
        String s1value;
        String s2value;
   DecimalFormat eachpayment = new DecimalFormat ("$###,##0.00");






     public MortgageGUI2a(){
        setLayout(new GridBagLayout());

        GridBagConstraints c= new GridBagConstraints();
         label1 = new JLabel("Mortgage Amount");                   //Mortgage label
         c.fill= GridBagConstraints.HORIZONTAL;
         c.gridx=0;
         c.gridy=0;
         add(label1,c);

         textfield1=new JTextField(15);                         //Mortgage Text
             c.fill=GridBagConstraints.HORIZONTAL;
            c.gridx=5;
            c.gridy=0;
            c.gridwidth=3;
             add (textfield1,c);


          label2=new JLabel("Interest Rate");                        //Interest label
           c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=2;
             c.gridwidth=1;
            add(label2,c);

            combo2 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=2;
            c.gridwidth=1;
            add(combo2,c);
            combo2.setEditable(true) ;

         ArrayList aa = new ArrayList();
         aa.add("Enter rate below");

         try{

         DataInputStream in = new DataInputStream(new FileInputStream("C:\\temp\\test\\rates.txt"));
             String buff = in.readLine();
             StringTokenizer t = new StringTokenizer(buff, " ,");
                while(t.hasMoreTokens())aa.add(t.nextToken());
             in.close();


         }
         catch(Exception ex){
             System.out.println("Error " + ex.toString());
             ex.printStackTrace();
         }
          String [] rates = new String[aa.size()];
         for(int j=0; j<aa.size(); j++){
                   rates[j] = (String) aa.get(j);
         }

            //combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Enter Rate below "," ", }));
           combo2.setModel(new javax.swing.DefaultComboBoxModel(rates));
                    combo2.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo2.getSelectedItem();
        textfield2.setText(str);
           s1value = str;
                        }

   });
        textfield2=new JTextField(15);                              //Interest Text
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=5;
             c.gridy=2;
             c.gridwidth=3;
             add (textfield2,c);
             textfield2.setEditable(false);
// textfield 2

        label3=new JLabel("Loan Term (Years)");                    //Number of Months Financed
          c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=3;
             c.gridwidth=1;
            add(label3,c);

             combo3 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=3;
            c.gridwidth=1;
            add(combo3,c);
            combo3.setEditable(false) ;
            combo3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Choose Term ","7","15","30" }));
                    combo3.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo3.getSelectedItem();
        textfield3.setText(str);
          s2value = str;

                        }

   });
        textfield3=new JTextField(15);                            // Loan Months
          c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=3;
             c.gridwidth=3;
            add (textfield3,c);
            textfield3.setEditable(false);
//textfield 3

             label4=new JLabel("Loan Term (Years)");                    //Number of Months Financed
              c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=4;
             c.gridwidth=1;
            add(label4,c);
            combo4 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=4;
            c.gridwidth=1;
            add(combo4,c);
             combo4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "?","7years at 5.35","15years at 5.5","30 years at 5.75" }));
                    combo4.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo4.getSelectedItem();
        textfield4.setText(str);
         System.out.println("str: " + str);
         s3value = str;
                        }

   });
            textfield4=new JTextField(15);                            // Loan Months
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=4;
             c.gridwidth=3;
            add (textfield4,c);
            textfield4.setEditable(false);

        label5=new JLabel("Payment");                                // Payment label
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=5;
             c.gridwidth=1;
            add(label5,c);


       textfield5=new JTextField(15);                               // Calculation Result
         c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=6;
             c.gridy=5;
             c.gridwidth=3;
             add (textfield5,c);
              textfield5.setEditable(false);

        
        Jbutton1=new JButton("Calculate");                          // Calculate Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=9;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton1,c);

        Jbutton1.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton1.addActionListener(new ActionListener() {            // Calculate Button Function

            public void itemStateChanged(ItemEvent event) {

  Object select = event.getItem();

              String selection = select.toString();
}
               public void actionPerformed(ActionEvent e) {

   if (e.getSource() == Jbutton1)

           {
              MortgageAmount = Double.parseDouble(textfield1.getText());
               //String s1 =    textfield2.getText().trim();
               String s1 = s1value;
                           System.out.println("s1 " + s1);
                 //String s2 =    textfield3.getText().trim();
                   String s2 = s2value;
                        System.out.println("s2 " + s1);



               if(s1==null || s1.equals("?")){
                  // String s3 =   textfield4.getText().trim();
                   String s3 = s3value;
                     System.out.println("s3 " + s3);
                    s1 = s3.substring(s3.indexOf("at")+2).trim();
                   System.out.println("s1 " + s1);
                     s2 = s3.substring(0,s3.indexOf("year")).trim();
                     System.out.println("s2 " + s2);

               }

             // userInterest = Double.parseDouble (textfield2.getText());
              //LoanTerm = Double.parseDouble (textfield3.getText());

               System.out.println("  s1 before " + s1);
                System.out.println("  s2 before " + s2);

               userInterest = Double.parseDouble (s1);
              LoanTerm = Double.parseDouble (s2);

			   CalculateMonthlyPayment() ;

               textfield5.setText(eachpayment.format(monthlyPayment));


			   repaint();
			   loanmonths = LoanTerm * 12;
			   loanBalance = MortgageAmount;

               String totalString = "";

              for (months = 1; months <= loanmonths; months++)
              {

                  //monthly interest calculation

                  monthlyInterest = userInterest / (1200.00);

                  //current months interest amount calculation

                  currentMonthInterest = loanBalance * monthlyInterest;

                  //current months principale amount calculation

                  currentMonthPrinciple = monthlyPayment - currentMonthInterest;

                  //current months interest minus loan amount
                 //provides new principle amount
                 loanBalance = loanBalance - currentMonthPrinciple;

                        totalString +=   "   Payment    " + months +   "           Monthly Payment    " + eachpayment.format(monthlyPayment)+
                                 "         Monthly Principle    " + eachpayment.format(currentMonthPrinciple)
                             +   "                Monthly Interest    " + eachpayment.format(currentMonthInterest)
                             +   "                    Loan Balance   "
                             + eachpayment.format(loanBalance) +   "\n";
        }
                      txtSubmitterComment.setText(totalString);
                    textfield4.setText(s3value);
                    textfield4.setForeground(Color.black);

                    }
            }




        });



        Jbutton2=new JButton("Clear");                             // Clear Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=6;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton2,c);





         txtSubmitterComment = new JTextArea(20,4);
         txtSubmitterComment.setLineWrap(false);
         txtSubmitterComment.setWrapStyleWord(false);
        // if(currentRecord.getSubmitter_comment() != null)
         txtSubmitterComment.setText("");
         paneForSubmitterComment = new JScrollPane(txtSubmitterComment);
           c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=20;
          add( paneForSubmitterComment,c);



          monthArea = new MyTextArea(200,200);

         String s = "test" + sep + "test1";
         monthArea.setText(s);


       scroll = new JScrollPane(monthArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            myPanel = new JPanel();
            myPanel.setPreferredSize(new Dimension(200,200));
             myPanel.setLayout(new BorderLayout());
                myPanel.add(scroll,BorderLayout.CENTER);

         JScrollPane pane = new JScrollPane();
            pane.setSize(100,100);
            pane.add(monthArea);
            c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=150;
             add(myPanel,c);
              scroll.revalidate();




         monthText = new JTextField[12];
            for (int jj=0; jj<monthText.length; jj++){
                monthText[jj] = new JTextField(70);
                 c.fill= GridBagConstraints.HORIZONTAL;
                  c.gridx=0;
             c.gridy=25 + 5*jj;
              c.gridwidth=20;
              c.gridheight=5;
             add (monthText[jj],c);
            }





        Jbutton2.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton2.addActionListener(new ActionListener() {             //Clear Button Function
               public void actionPerformed(ActionEvent e) {
                combo3.setSelectedIndex(0);
                combo2.setSelectedIndex(0);
                combo4.setSelectedIndex(0);
                textfield1.setText("");
                textfield2.setText("");
                textfield3.setText("");
                textfield4.setText("");
                textfield5.setText("");

                   txtSubmitterComment.setText("");
                     for (int jj=0; jj<monthText.length; jj++){
                         monthText[jj].setText("");
                     }
                paymentCounter = 0;



              // TODO add your handling code here:;
             }

        });


         Jbutton3=new JButton("Exit");                                  //Exit Button
           c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=0;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton3,c);

        Jbutton3.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton3.addActionListener(new ActionListener() {               //Exit Button Function
               public void actionPerformed(ActionEvent e) {
                   System.exit(0);
            }
        });

        Jbutton4=new JButton ("Chart");
         c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=20;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton4,c);

         Jbutton4.addActionListener(new ActionListener() {               //Chart Button Function
               public void actionPerformed(ActionEvent e) 
                   
                    try{

         DataInputStream in = new DataInputStream(new FileInputStream("C:\\temp\\test\\piechart.txt"));
             String buff = in.readLine();
             StringTokenizer t = new StringTokenizer(buff, " ,");
                while(t.hasMoreTokens())aa.add(t.nextToken());
             in.close();


         }
         catch(Exception ex){
             System.out.println("Error " + ex.toString());
             ex.printStackTrace();
         
          
         }
     
             
         
         event evt = new event();
        Jbutton1.addActionListener(evt);
        Jbutton2.addActionListener(evt);
        Jbutton3.addActionListener(evt);
        Jbutton4.addActionListener(evt);
   }
    double CalculateMonthlyPayment()       {

        String s1 =    textfield2.getText().trim();
                       System.out.println("s1 " + s1);
             String s2 =    textfield3.getText().trim();
                    System.out.println("s2 " + s1);

           if(s1==null || s1.equals("")){
              // String s3 =   textfield4.getText().trim();
               String s3 = s3value;
                 System.out.println("s3 " + s3);
                s1 = s3.substring(s3.indexOf("at")+2).trim();
               System.out.println("s1 " + s1);
                 s2 = s3.substring(0,s3.indexOf("year")).trim();
                 System.out.println("s2 " + s2);

           }


        //Parse text to Float Type
       MortgageAmount=Float.parseFloat(textfield1.getText());

         LoanTerm=Float.parseFloat(s2);
       monthlyInterest=Float.parseFloat(s1);

      //LoanTerm=Float.parseFloat(textfield3.getText());
       //monthlyInterest=Float.parseFloat(textfield2.getText());





       paymentCounter += counter + 1;

           return monthlyPayment = ((MortgageAmount * monthlyInterest / 100 / 12) / (1 - Math.pow(1 + monthlyInterest / 100 / 12, - LoanTerm *12)));



   }
   {

   }
     public class event implements ActionListener {
        public void actionPerformed(ActionEvent evt ) {








        }





   }


   public static void main (String args[]){                                  //GUI Frame
       MortgageGUI2a gui= new MortgageGUI2a();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(900,900);
        gui.setVisible(true);
       gui.setTitle("Mortgage Calculator");


    }
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JButton Jbutton4;
    JButton Jbutton1;
    JButton Jbutton2;
    JButton Jbutton3;
    JTextField textfield1;
    JTextField textfield2;
    JTextField textfield3;
    JTextField textfield4;
    JTextField textfield5;
    JComboBox combo2;
    JComboBox combo3;
    JComboBox combo4;
    JTextField[] monthText;
    MyTextArea monthArea;
    JPanel myPanel;
    JScrollPane scroll;
    JTextArea txtSubmitterComment;
    JScrollPane paneForSubmitterComment;





    }

class MyTextArea extends JTextArea{

    public MyTextArea(int x, int y){
        super(x,y);
    }
    public Dimension setPreferredSize(){
        Dimension d = new Dimension (200,200);
        return d;

    }
}

Open in new window

piechart.txt rates.txt

Sorry, was not able to modfy your latest code.

This is based on the  code I sent you pevious time  and the bar chart
comes form modified code from objects suggestion above.

Hope you can draw bar chart instead of the piechart.


 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MortgageGUI2;

/**
 *
 * @author robertwalters
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

  // package MortgageGUI2;

   /**
*
* @author robertwalters
*/

   import java.awt.*;
   import java.awt.Color.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.lang.Math.*;
   import java.text.DecimalFormat;         //Import for decimal points
   import java.text.SimpleDateFormat;
   import java.text.ParsePosition;
   import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
   import java.io.DataInputStream;
   import java.io.FileInputStream;
   import java.util.StringTokenizer;
   import java.util.ArrayList;


 public class MortgageGUI2a extends JFrame  {
       static String sep = System.getProperty("line.separator");
    double MortgageAmount = 0;                    //Variable Mortgage
   double  LoanTerm  = 0.0;
   double loanmonths= 0.0;//Number of Months
   double [] InterestRate = {.0535,.055,.0575};                      //Interest Rate for Loan
    double monthlyInterest = 0;
   int[] years = {1,7,15,30};
   int  months = 0;
    double monthlyPayment = 0.00;
   double loanBalance = 0;
    double currentMonthInterest = 0.00 ;
   double currentMonthPrinciple = 0.00;
   int counter = 0;
   int paymentCounter = 0;
   int breakCounter = 0;
    double userInterest = 0.0;
   double princPayment = 0;
   double remainMortgage=0;
       String s3value;
        String s1value;
        String s2value;
   DecimalFormat eachpayment = new DecimalFormat ("$###,##0.00");






     public MortgageGUI2a(){
        setLayout(new GridBagLayout());

        GridBagConstraints c= new GridBagConstraints();
         label1 = new JLabel("Mortgage Amount");                   //Mortgage label
         c.fill= GridBagConstraints.HORIZONTAL;
         c.gridx=0;
         c.gridy=0;
         add(label1,c);
 
         textfield1=new JTextField(15);                         //Mortgage Text
             c.fill=GridBagConstraints.HORIZONTAL;
            c.gridx=5;
            c.gridy=0;
            c.gridwidth=3;
             add (textfield1,c);


          label2=new JLabel("Interest Rate");                        //Interest label
           c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=2;
             c.gridwidth=1;
            add(label2,c);

            combo2 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=2;
            c.gridwidth=1;
            add(combo2,c);
            combo2.setEditable(true) ;

         ArrayList aa = new ArrayList();
         aa.add("Enter rate below");

         try{

         DataInputStream in = new DataInputStream(new FileInputStream("C:\\temp\\test\\rates.txt"));
             String buff = in.readLine();
             StringTokenizer t = new StringTokenizer(buff, " ,");
                while(t.hasMoreTokens())aa.add(t.nextToken());
             in.close();


         }
         catch(Exception ex){
             System.out.println("Error " + ex.toString());
             ex.printStackTrace();
         }
          String [] rates = new String[aa.size()];
         for(int j=0; j<aa.size(); j++){
                   rates[j] = (String) aa.get(j);
         }

            //combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Enter Rate below "," ", }));
           combo2.setModel(new javax.swing.DefaultComboBoxModel(rates));
                    combo2.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo2.getSelectedItem();
        textfield2.setText(str);
           s1value = str;
                        }

   });
        textfield2=new JTextField(15);                              //Interest Text
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=5;
             c.gridy=2;
             c.gridwidth=3;
             add (textfield2,c);
             textfield2.setEditable(false);
// textfield 2

        label3=new JLabel("Loan Term (Years)");                    //Number of Months Financed
          c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=3;
             c.gridwidth=1;
            add(label3,c);

             combo3 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=3;
            c.gridwidth=1;
            add(combo3,c);
            combo3.setEditable(false) ;
            combo3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {" ","7","15","30" }));
                    combo3.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo3.getSelectedItem();
        textfield3.setText(str);
          s2value = str;

                        }

   });
        textfield3=new JTextField(15);                            // Loan Months
          c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=3;
             c.gridwidth=3;
            add (textfield3,c);
            textfield3.setEditable(false);
//textfield 3

             label4=new JLabel("Loan Term (Years)");                    //Number of Months Financed
              c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=4;
             c.gridwidth=1;
            add(label4,c);
            combo4 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=4;
            c.gridwidth=1;
            add(combo4,c);
             combo4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "?","7years at 5.35","15years at 5.5","30 years at 5.75" }));
                    combo4.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo4.getSelectedItem();
        textfield4.setText(str);
         System.out.println("str: " + str);
         s3value = str;
                        }

   });
            textfield4=new JTextField(15);                            // Loan Months
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=4;
             c.gridwidth=3;
            add (textfield4,c);
            textfield4.setEditable(false);

        label5=new JLabel("Payment");                                // Payment label
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=5;
             c.gridwidth=1;
            add(label5,c);


       textfield5=new JTextField(15);                               // Calculation Result
         c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=6;
             c.gridy=5;
             c.gridwidth=3;
             add (textfield5,c);
              textfield5.setEditable(false);



        Jbutton1=new JButton("Calculate");                          // Calculate Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=9;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton1,c);

        Jbutton1.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton1.addActionListener(new ActionListener() {            // Calculate Button Function

            public void itemStateChanged(ItemEvent event) {

  Object select = event.getItem();

              String selection = select.toString();
}
               public void actionPerformed(ActionEvent e) {

   if (e.getSource() == Jbutton1)

           {
              MortgageAmount = Double.parseDouble(textfield1.getText());
               //String s1 =    textfield2.getText().trim();
               String s1 = s1value;
                           System.out.println("s1 " + s1);
                 //String s2 =    textfield3.getText().trim();
                   String s2 = s2value;
                        System.out.println("s2 " + s1);



               if(s1==null || s1.equals("?")){
                  // String s3 =   textfield4.getText().trim();
                   String s3 = s3value;
                     System.out.println("s3 " + s3);
                    s1 = s3.substring(s3.indexOf("at")+2).trim();
                   System.out.println("s1 " + s1);
                     s2 = s3.substring(0,s3.indexOf("year")).trim();
                     System.out.println("s2 " + s2);

               }

             // userInterest = Double.parseDouble (textfield2.getText());
              //LoanTerm = Double.parseDouble (textfield3.getText());

               System.out.println("  s1 before " + s1);
                System.out.println("  s2 before " + s2);

               userInterest = Double.parseDouble (s1);
              LoanTerm = Double.parseDouble (s2);

			   CalculateMonthlyPayment() ;

               textfield5.setText(eachpayment.format(monthlyPayment));


			   repaint();
			   loanmonths = LoanTerm * 12;
			   loanBalance = MortgageAmount;

               String totalString = "";

               BarChart bc = new  BarChart();

              for (months = 1; months <= loanmonths; months++)
              {

                  //monthly interest calculation

                  monthlyInterest = userInterest / (1200.00);

                  //current months interest amount calculation

                  currentMonthInterest = loanBalance * monthlyInterest;

                  //current months principale amount calculation

                  currentMonthPrinciple = monthlyPayment - currentMonthInterest;

                  //current months interest minus loan amount
                 //provides new principle amount
                 loanBalance = loanBalance - currentMonthPrinciple;

                        totalString +=   "   Payment    " + months +   "           Monthly Payment    " + eachpayment.format(monthlyPayment)+
                                 "         Monthly Principle    " + eachpayment.format(currentMonthPrinciple)
                             +   "                Monthly Interest    " + eachpayment.format(currentMonthInterest)
                             +   "                    Loan Balance   "
                             + eachpayment.format(loanBalance) +   "\n";

                if((months%2)==0)  bc.addBar(Color.GREEN, (int) (loanBalance+0.5f));
                  else  bc.addBar(Color.RED, (int) (loanBalance+0.5f));

        }


      JFrame frame = new JFrame("Bar Chart - Loan Balance");
     frame.getContentPane().add(bc);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();
               frame.setSize(700,500);
frame.setVisible(true); 

                      txtSubmitterComment.setText(totalString);
                    textfield4.setText(s3value);
                    textfield4.setForeground(Color.black);

                    }


            }




        });



        Jbutton2=new JButton("Clear");                             // Clear Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=6;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton2,c);





         txtSubmitterComment = new JTextArea(20,4);
         txtSubmitterComment.setLineWrap(false);
         txtSubmitterComment.setWrapStyleWord(false);
        // if(currentRecord.getSubmitter_comment() != null)
         txtSubmitterComment.setText("");
         paneForSubmitterComment = new JScrollPane(txtSubmitterComment);
           c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=20;
          add( paneForSubmitterComment,c);



          monthArea = new MyTextArea(200,200);

         String s = "test" + sep + "test1";
         monthArea.setText(s);


       scroll = new JScrollPane(monthArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            myPanel = new JPanel();
            myPanel.setPreferredSize(new Dimension(200,200));
             myPanel.setLayout(new BorderLayout());
                myPanel.add(scroll,BorderLayout.CENTER);

         JScrollPane pane = new JScrollPane();
            pane.setSize(100,100);
            pane.add(monthArea);
            c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=150;
             add(myPanel,c);
              scroll.revalidate();




         monthText = new JTextField[12];
            for (int jj=0; jj<monthText.length; jj++){
                monthText[jj] = new JTextField(70);
                 c.fill= GridBagConstraints.HORIZONTAL;
                  c.gridx=0;
             c.gridy=25 + 5*jj;
              c.gridwidth=20;
              c.gridheight=5;
             add (monthText[jj],c);
            }





        Jbutton2.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton2.addActionListener(new ActionListener() {             //Clear Button Function
               public void actionPerformed(ActionEvent e) {
                combo3.setSelectedIndex(0);
                combo2.setSelectedIndex(0);
                combo4.setSelectedIndex(0);
                textfield1.setText("");
                textfield2.setText("");
                textfield3.setText("");
                textfield4.setText("");
                textfield5.setText("");

                   txtSubmitterComment.setText("");
                     for (int jj=0; jj<monthText.length; jj++){
                         monthText[jj].setText("");
                     }
                paymentCounter = 0;



              // TODO add your handling code here:;
             }

        });


         Jbutton3=new JButton("Exit");                                  //Exit Button
           c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=0;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton3,c);

        Jbutton3.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton3.addActionListener(new ActionListener() {               //Exit Button Function
               public void actionPerformed(ActionEvent e) {
                   System.exit(0);
            }
        });


         event evt = new event();
        Jbutton1.addActionListener(evt);
        Jbutton2.addActionListener(evt);
        Jbutton3.addActionListener(evt);
   }
    double CalculateMonthlyPayment()       {

        String s1 =    textfield2.getText().trim();
                       System.out.println("s1 " + s1);
             String s2 =    textfield3.getText().trim();
                    System.out.println("s2 " + s1);

           if(s1==null || s1.equals("")){
              // String s3 =   textfield4.getText().trim();
               String s3 = s3value;
                 System.out.println("s3 " + s3);
                s1 = s3.substring(s3.indexOf("at")+2).trim();
               System.out.println("s1 " + s1);
                 s2 = s3.substring(0,s3.indexOf("year")).trim();
                 System.out.println("s2 " + s2);

           }


        //Parse text to Float Type
       MortgageAmount=Float.parseFloat(textfield1.getText());

         LoanTerm=Float.parseFloat(s2);
       monthlyInterest=Float.parseFloat(s1);

      //LoanTerm=Float.parseFloat(textfield3.getText());
       //monthlyInterest=Float.parseFloat(textfield2.getText());





       paymentCounter += counter + 1;

           return monthlyPayment = ((MortgageAmount * monthlyInterest / 100 / 12) / (1 - Math.pow(1 + monthlyInterest / 100 / 12, - LoanTerm *12)));



   }
   {

   }
     public class event implements ActionListener {
        public void actionPerformed(ActionEvent evt ) {








        }





   }


   public static void main (String args[]){                                  //GUI Frame
       MortgageGUI2a gui= new MortgageGUI2a();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(900,900);
        gui.setVisible(true);
       gui.setTitle("Mortgage Calculator");


    }
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JButton JButton4;
    JButton Jbutton1;
    JButton Jbutton2;
    JButton Jbutton3;
    JTextField textfield1;
    JTextField textfield2;
    JTextField textfield3;
    JTextField textfield4;
    JTextField textfield5;
    JComboBox combo2;
    JComboBox combo3;
    JComboBox combo4;
    JTextField[] monthText;
    MyTextArea monthArea;
    JPanel myPanel;
    JScrollPane scroll;
    JTextArea txtSubmitterComment;
    JScrollPane paneForSubmitterComment;





    }

class MyTextArea extends JTextArea{

    public MyTextArea(int x, int y){
        super(x,y);
    }
    public Dimension setPreferredSize(){
        Dimension d = new Dimension (200,200);
        return d;

    }
}

Open in new window



package MortgageGUI2;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BarChart extends JPanel
{
	//private Map bars =
      //      new LinkedHashMap();

    //private HashMap bars = new HashMap();
    private ArrayList aa = new ArrayList();
    private ArrayList cc = new ArrayList();

    /**
	 * Add new bar to chart
	 * @param color color to display bar
	 * @param value size of bar
	 */
	public void addBar(Color color, int value)
	{
        aa.add(new Integer(value));
        cc.add(color);
      //  bars.put(new Integer(value), color);
       // bars.put(color, new Integer(value));
		repaint();
	}

//	@Override
	protected void paintComponent(Graphics g)
	{
		// determine longest bar

		int max = Integer.MIN_VALUE;

        for (int j=0; j<aa.size(); j++){
            max = Math.max(max,((Integer)aa.get(j)).intValue());

        }
        /*
        Collection val = bars.values();
        Iterator iter = val.iterator();
        while(iter.hasNext()){
            max = Math.max(max, ((Integer)iter.next()).intValue());
        }
        */
        /*
        for (Integer value : bars.values())
		{
			max = Math.max(max, value);
		}
        */

        // paint bars

		int width = (getWidth() / aa.size()) - 2;
		int x = 1;

        for(int j=0; j<aa.size(); j++){

        int value = ((Integer) aa.get(j)).intValue();
          Color color = (Color) cc.get(j);
            /*
            Set kkeys = bars.keySet();
            Iterator iter1 = kkeys.iterator();
          while(iter1.hasNext()){
              Color color = (Color) iter1.next();
    //      }
  //      for (Color color : bars.keySet())
//		{
			int value = ((Integer)bars.get(color)).intValue();
              */
            int height = (int)
                            ((getHeight()-5) * ((double)value / max));
			g.setColor(color);
			g.fillRect(x, getHeight() - height, width, height);
			g.setColor(Color.black);
			g.drawRect(x, getHeight() - height, width, height);
			x += (width + 2);
		}
	}

//	@Override
	public Dimension getPreferredSize() {
		return new Dimension(aa.size() * 10 + 2, 50);
	}

	public static void main(String[] args)
	{
		JFrame frame = new JFrame("Bar Chart");
		BarChart chart = new BarChart();
		chart.addBar(Color.red, 100);
		chart.addBar(Color.green, 8);
		chart.addBar(Color.blue, 54);
		chart.addBar(Color.black, 23);
		frame.getContentPane().add(chart);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}

Open in new window

Avatar of zomrob

ASKER

Ok I figured there was something easier than what I have been trying. I put them both in the same code and it works great.  One question , how would I show the left side of the graph a principal, and across the bottom as payments. This would show comparison as payments are made, the principal goes down. I want to label each so the instructor knows what is going on.

Again I appreciate your help. Here is the code combined.

 
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MortgageGUI2;

/**
 *
 * @author robertwalters
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

  // package MortgageGUI2;

   /**
*
* @author robertwalters
*/

   import java.awt.*;
   import java.awt.Color.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.lang.Math.*;
   import java.text.DecimalFormat;         //Import for decimal points
   import java.text.SimpleDateFormat;
   import java.text.ParsePosition;
   import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
   import java.io.DataInputStream;
   import java.io.FileInputStream;
   import java.util.StringTokenizer;
   import java.util.ArrayList;
   import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;




 public class MortgageGUI2a extends JFrame  {
       static String sep = System.getProperty("line.separator");
    double MortgageAmount = 0;                    //Variable Mortgage
   double  LoanTerm  = 0.0;
   double loanmonths= 0.0;//Number of Months
   double [] InterestRate = {.0535,.055,.0575};                      //Interest Rate for Loan
    double monthlyInterest = 0;
   int[] years = {1,7,15,30};
   int  months = 0;
    double monthlyPayment = 0.00;
   double loanBalance = 0;
    double currentMonthInterest = 0.00 ;
   double currentMonthPrinciple = 0.00;
   int counter = 0;
   int paymentCounter = 0;
   int breakCounter = 0;
    double userInterest = 0.0;
   double princPayment = 0;
   double remainMortgage=0;
       String s3value;
        String s1value;
        String s2value;
   DecimalFormat eachpayment = new DecimalFormat ("$###,##0.00");






     public MortgageGUI2a(){
        setLayout(new GridBagLayout());

        GridBagConstraints c= new GridBagConstraints();
         label1 = new JLabel("Mortgage Amount");                   //Mortgage label
         c.fill= GridBagConstraints.HORIZONTAL;
         c.gridx=0;
         c.gridy=0;
         add(label1,c);

         textfield1=new JTextField(15);                         //Mortgage Text
             c.fill=GridBagConstraints.HORIZONTAL;
            c.gridx=5;
            c.gridy=0;
            c.gridwidth=3;
             add (textfield1,c);


          label2=new JLabel("Interest Rate");                        //Interest label
           c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=2;
             c.gridwidth=1;
            add(label2,c);

            combo2 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=2;
            c.gridwidth=1;
            add(combo2,c);
            combo2.setEditable(true) ;

         ArrayList aa = new ArrayList();
         aa.add("Enter rate below");

         try{

         DataInputStream in = new DataInputStream(new FileInputStream("C:\\temp\\test\\rates.txt"));
             String buff = in.readLine();
             StringTokenizer t = new StringTokenizer(buff, " ,");
                while(t.hasMoreTokens())aa.add(t.nextToken());
             in.close();


         }
         catch(Exception ex){
             System.out.println("Error " + ex.toString());
             ex.printStackTrace();
         }
          String [] rates = new String[aa.size()];
         for(int j=0; j<aa.size(); j++){
                   rates[j] = (String) aa.get(j);
         }

            //combo2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Enter Rate below "," ", }));
           combo2.setModel(new javax.swing.DefaultComboBoxModel(rates));
                    combo2.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo2.getSelectedItem();
        textfield2.setText(str);
           s1value = str;
                        }

   });
        textfield2=new JTextField(15);                              //Interest Text
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=5;
             c.gridy=2;
             c.gridwidth=3;
             add (textfield2,c);
             textfield2.setEditable(false);
// textfield 2

        label3=new JLabel("Loan Term (Years)");                    //Number of Months Financed
          c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=3;
             c.gridwidth=1;
            add(label3,c);

             combo3 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=3;
            c.gridwidth=1;
            add(combo3,c);
            combo3.setEditable(false) ;
            combo3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {" ","7","15","30" }));
                    combo3.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo3.getSelectedItem();
        textfield3.setText(str);
          s2value = str;

                        }

   });
        textfield3=new JTextField(15);                            // Loan Months
          c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=3;
             c.gridwidth=3;
            add (textfield3,c);
            textfield3.setEditable(false);
//textfield 3

             label4=new JLabel("Loan Term (Years)");                    //Number of Months Financed
              c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=4;
             c.gridwidth=1;
            add(label4,c);
            combo4 = new JComboBox();
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=2;
            c.gridy=4;
            c.gridwidth=1;
            add(combo4,c);
             combo4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "?","7years at 5.35","15years at 5.5","30 years at 5.75" }));
                    combo4.addItemListener(new ItemListener(){
     public void itemStateChanged(ItemEvent ie){
       String str = (String)combo4.getSelectedItem();
        textfield4.setText(str);
         System.out.println("str: " + str);
         s3value = str;
                        }

   });
            textfield4=new JTextField(15);                            // Loan Months
            c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=5;
             c.gridy=4;
             c.gridwidth=3;
            add (textfield4,c);
            textfield4.setEditable(false);

        label5=new JLabel("Payment");                                // Payment label
         c.fill= GridBagConstraints.HORIZONTAL;
             c.gridx=0;
             c.gridy=5;
             c.gridwidth=1;
            add(label5,c);


       textfield5=new JTextField(15);                               // Calculation Result
         c.fill= GridBagConstraints.HORIZONTAL;
            c.gridx=6;
             c.gridy=5;
             c.gridwidth=3;
             add (textfield5,c);
              textfield5.setEditable(false);



        Jbutton1=new JButton("Calculate");                          // Calculate Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=9;
        c.gridy=15;
        c.gridwidth=1;
         add (Jbutton1,c);

        Jbutton1.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton1.addActionListener(new ActionListener() {            // Calculate Button Function

            public void itemStateChanged(ItemEvent event) {

  Object select = event.getItem();

              String selection = select.toString();
}
               public void actionPerformed(ActionEvent e) {

   if (e.getSource() == Jbutton1)

           {
              MortgageAmount = Double.parseDouble(textfield1.getText());
               //String s1 =    textfield2.getText().trim();
               String s1 = s1value;
                           System.out.println("s1 " + s1);
                 //String s2 =    textfield3.getText().trim();
                   String s2 = s2value;
                        System.out.println("s2 " + s1);



               if(s1==null || s1.equals("?")){
                  // String s3 =   textfield4.getText().trim();
                   String s3 = s3value;
                     System.out.println("s3 " + s3);
                    s1 = s3.substring(s3.indexOf("at")+2).trim();
                   System.out.println("s1 " + s1);
                     s2 = s3.substring(0,s3.indexOf("year")).trim();
                     System.out.println("s2 " + s2);

               }

             // userInterest = Double.parseDouble (textfield2.getText());
              //LoanTerm = Double.parseDouble (textfield3.getText());

               System.out.println("  s1 before " + s1);
                System.out.println("  s2 before " + s2);

               userInterest = Double.parseDouble (s1);
              LoanTerm = Double.parseDouble (s2);

			   CalculateMonthlyPayment() ;

               textfield5.setText(eachpayment.format(monthlyPayment));


			   repaint();
			   loanmonths = LoanTerm * 12;
			   loanBalance = MortgageAmount;

               String totalString = "";

               BarChart bc = new  BarChart();

              for (months = 1; months <= loanmonths; months++)
              {

                  //monthly interest calculation

                  monthlyInterest = userInterest / (1200.00);

                  //current months interest amount calculation

                  currentMonthInterest = loanBalance * monthlyInterest;

                  //current months principale amount calculation

                  currentMonthPrinciple = monthlyPayment - currentMonthInterest;

                  //current months interest minus loan amount
                 //provides new principle amount
                 loanBalance = loanBalance - currentMonthPrinciple;

                        totalString +=   "   Payment    " + months +   "           Monthly Payment    " + eachpayment.format(monthlyPayment)+
                                 "         Monthly Principle    " + eachpayment.format(currentMonthPrinciple)
                             +   "                Monthly Interest    " + eachpayment.format(currentMonthInterest)
                             +   "                    Loan Balance   "
                             + eachpayment.format(loanBalance) +   "\n";

                if((months%2)==0)  bc.addBar(Color.GREEN, (int) (loanBalance+0.5f));
                  else  bc.addBar(Color.RED, (int) (loanBalance+0.5f));

        }


      JFrame frame = new JFrame("Bar Chart - Loan Balance");
     frame.getContentPane().add(bc);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();
               frame.setSize(700,500);
frame.setVisible(true);

                      txtSubmitterComment.setText(totalString);
                    textfield4.setText(s3value);
                    textfield4.setForeground(Color.black);

                    }


            }




        });



        Jbutton2=new JButton("Clear");                             // Clear Button
        c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=6;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton2,c);





         txtSubmitterComment = new JTextArea(20,4);
         txtSubmitterComment.setLineWrap(false);
         txtSubmitterComment.setWrapStyleWord(false);
        // if(currentRecord.getSubmitter_comment() != null)
         txtSubmitterComment.setText("");
         paneForSubmitterComment = new JScrollPane(txtSubmitterComment);
           c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=20;
          add( paneForSubmitterComment,c);



          monthArea = new MyTextArea(200,200);

         String s = "test" + sep + "test1";
         monthArea.setText(s);


       scroll = new JScrollPane(monthArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            myPanel = new JPanel();
            myPanel.setPreferredSize(new Dimension(200,200));
             myPanel.setLayout(new BorderLayout());
                myPanel.add(scroll,BorderLayout.CENTER);

         JScrollPane pane = new JScrollPane();
            pane.setSize(100,100);
            pane.add(monthArea);
            c.fill= GridBagConstraints.BOTH;
                  c.gridx=0;
             c.gridy=25;
              c.gridwidth=20;
              c.gridheight=150;
             add(myPanel,c);
              scroll.revalidate();




         monthText = new JTextField[12];
            for (int jj=0; jj<monthText.length; jj++){
                monthText[jj] = new JTextField(70);
                 c.fill= GridBagConstraints.HORIZONTAL;
                  c.gridx=0;
             c.gridy=25 + 5*jj;
              c.gridwidth=20;
              c.gridheight=5;
             add (monthText[jj],c);
            }





        Jbutton2.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton2.addActionListener(new ActionListener() {             //Clear Button Function
               public void actionPerformed(ActionEvent e) {
                combo3.setSelectedIndex(0);
                combo2.setSelectedIndex(0);
                combo4.setSelectedIndex(0);
                textfield1.setText("");
                textfield2.setText("");
                textfield3.setText("");
                textfield4.setText("");
                textfield5.setText("");

                   txtSubmitterComment.setText("");
                     for (int jj=0; jj<monthText.length; jj++){
                         monthText[jj].setText("");
                     }
                paymentCounter = 0;



              // TODO add your handling code here:;
             }

        });


         Jbutton3=new JButton("Exit");                                  //Exit Button
           c.fill=GridBagConstraints.HORIZONTAL;
        c.gridx=0;
        c.gridy=15;
        c.gridwidth=1;
        add(Jbutton3,c);

        Jbutton3.setMnemonic(KeyEvent.VK_I);	//Set ShortCut Keys

        Jbutton3.addActionListener(new ActionListener() {               //Exit Button Function
               public void actionPerformed(ActionEvent e) {
                   System.exit(0);
            }
        });


         event evt = new event();
        Jbutton1.addActionListener(evt);
        Jbutton2.addActionListener(evt);
        Jbutton3.addActionListener(evt);
   }
    double CalculateMonthlyPayment()       {

        String s1 =    textfield2.getText().trim();
                       System.out.println("s1 " + s1);
             String s2 =    textfield3.getText().trim();
                    System.out.println("s2 " + s1);

           if(s1==null || s1.equals("")){
              // String s3 =   textfield4.getText().trim();
               String s3 = s3value;
                 System.out.println("s3 " + s3);
                s1 = s3.substring(s3.indexOf("at")+2).trim();
               System.out.println("s1 " + s1);
                 s2 = s3.substring(0,s3.indexOf("year")).trim();
                 System.out.println("s2 " + s2);

           }


        //Parse text to Float Type
       MortgageAmount=Float.parseFloat(textfield1.getText());

         LoanTerm=Float.parseFloat(s2);
       monthlyInterest=Float.parseFloat(s1);

      //LoanTerm=Float.parseFloat(textfield3.getText());
       //monthlyInterest=Float.parseFloat(textfield2.getText());





       paymentCounter += counter + 1;

           return monthlyPayment = ((MortgageAmount * monthlyInterest / 100 / 12) / (1 - Math.pow(1 + monthlyInterest / 100 / 12, - LoanTerm *12)));



   }
   {

   }
     public class event implements ActionListener {
        public void actionPerformed(ActionEvent evt ) {








        }





   }


   public static void main (String args[]){                                  //GUI Frame
       MortgageGUI2a gui= new MortgageGUI2a();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(900,900);
        gui.setVisible(true);
       gui.setTitle("Mortgage Calculator");


    }
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JButton JButton4;
    JButton Jbutton1;
    JButton Jbutton2;
    JButton Jbutton3;
    JTextField textfield1;
    JTextField textfield2;
    JTextField textfield3;
    JTextField textfield4;
    JTextField textfield5;
    JComboBox combo2;
    JComboBox combo3;
    JComboBox combo4;
    JTextField[] monthText;
    MyTextArea monthArea;
    JPanel myPanel;
    JScrollPane scroll;
    JTextArea txtSubmitterComment;
    JScrollPane paneForSubmitterComment;





    }

class MyTextArea extends JTextArea{

    public MyTextArea(int x, int y){
        super(x,y);
    }
    public Dimension setPreferredSize(){
        Dimension d = new Dimension (200,200);
        return d;

    }
}

     class BarChart extends JPanel
{
	//private Map bars =
      //      new LinkedHashMap();

    //private HashMap bars = new HashMap();
    private ArrayList aa = new ArrayList();
    private ArrayList cc = new ArrayList();

    /**
	 * Add new bar to chart
	 * @param color color to display bar
	 * @param value size of bar
	 */
	public void addBar(Color color, int value)
	{
        aa.add(new Integer(value));
        cc.add(color);
      //  bars.put(new Integer(value), color);
       // bars.put(color, new Integer(value));
		repaint();
	}

//	@Override
	protected void paintComponent(Graphics g)
	{
		// determine longest bar

		int max = Integer.MIN_VALUE;

        for (int j=0; j<aa.size(); j++){
            max = Math.max(max,((Integer)aa.get(j)).intValue());

        }
        /*
        Collection val = bars.values();
        Iterator iter = val.iterator();
        while(iter.hasNext()){
            max = Math.max(max, ((Integer)iter.next()).intValue());
        }
        */
        /*
        for (Integer value : bars.values())
		{
			max = Math.max(max, value);
		}
        */

        // paint bars

		int width = (getWidth() / aa.size()) - 2;
		int x = 1;

        for(int j=0; j<aa.size(); j++){

        int value = ((Integer) aa.get(j)).intValue();
          Color color = (Color) cc.get(j);
            /*
            Set kkeys = bars.keySet();
            Iterator iter1 = kkeys.iterator();
          while(iter1.hasNext()){
              Color color = (Color) iter1.next();
    //      }
  //      for (Color color : bars.keySet())
//		{
			int value = ((Integer)bars.get(color)).intValue();
              */
            int height = (int)
                            ((getHeight()-5) * ((double)value / max));
			g.setColor(color);
			g.fillRect(x, getHeight() - height, width, height);
			g.setColor(Color.black);
			g.drawRect(x, getHeight() - height, width, height);
			x += (width + 2);
		}
	}

//	@Override
	public Dimension getPreferredSize() {
		return new Dimension(aa.size() * 10 + 2, 50);
	}

	public static void main(String[] args)
	{
		JFrame frame = new JFrame("Bar Chart");
		BarChart chart = new BarChart();
		chart.addBar(Color.red, 100);
		chart.addBar(Color.green, 8);
		chart.addBar(Color.blue, 54);
		chart.addBar(Color.black, 23);
		frame.getContentPane().add(chart);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}

Open in new window

You want to accumulate the numbers which we have in the column monthly payment and make this sum horizontally
and then place numbers in clumn principal - vertically? But we don't see numbers in principal going down?
Avatar of zomrob

ASKER

Ok so I figured out that I do not need to combine them , makes sense. (I figured if I was you would have done that). So as long as I have the two classes in the same package they work together. Right?
Yea learned something...

I still would like to be able to label the principal and payments sections. Thanks
Well first let's decide what you want to be on the axes - still not quite understandable - see my question above.
Avatar of zomrob

ASKER

I am not worried about numbers. I tried to enclose a drawing of what is needed. All it shows is the relation
of the principal and payment, when a payment is made the principal goes down.

hope this is clearer.


 User generated image
Still don't understand - you mean you don't care what plot is actually shown inside - just those bars which I showed before
will be OK if we just label the axes ? If that is not so, and you do care. then let me know
which data you want to see in the plot.
I don't think we can draw axis name vertically - we can put it horizonatlly at the top of the axis
Avatar of zomrob

ASKER

Yea, I just need to label the axes. and putting one horizontally at the top is fine.


Just BarChart class needs to be replaced.
main class does not need to be changed.

You may want to clean up all those lnes below which are commented out.


package MortgageGUI2;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BarChart extends JPanel
{
	//private Map bars =
      //      new LinkedHashMap();

    //private HashMap bars = new HashMap();
    private ArrayList aa = new ArrayList();
    private ArrayList cc = new ArrayList();

    /**
	 * Add new bar to chart
	 * @param color color to display bar
	 * @param value size of bar
	 */
	public void addBar(Color color, int value)
	{
        aa.add(new Integer(value));
        cc.add(color);
      //  bars.put(new Integer(value), color);
       // bars.put(color, new Integer(value));
		repaint();
	}

//	@Override
	protected void paintComponent(Graphics g)
	{
		// determine longest bar

		int max = Integer.MIN_VALUE;

        for (int j=0; j<aa.size(); j++){
            max = Math.max(max,((Integer)aa.get(j)).intValue());

        }
        /*
        Collection val = bars.values();
        Iterator iter = val.iterator();
        while(iter.hasNext()){
            max = Math.max(max, ((Integer)iter.next()).intValue());
        }
        */
        /*
        for (Integer value : bars.values())
		{
			max = Math.max(max, value);
		}
        */

        // paint bars

		int width = (int)(getWidth()*0.90 / aa.size()) - 2;
		//int x = 1;

        int x = (int) (getWidth()*0.10);

        for(int j=0; j<aa.size(); j++){

        int value = ((Integer) aa.get(j)).intValue();
          Color color = (Color) cc.get(j);
            /*
            Set kkeys = bars.keySet();
            Iterator iter1 = kkeys.iterator();
          while(iter1.hasNext()){
              Color color = (Color) iter1.next();
    //      }
  //      for (Color color : bars.keySet())
//		{
			int value = ((Integer)bars.get(color)).intValue();
              */
            int height = (int)
                            ((getHeight()-5)* 0.90 * ((double)value / max));
			g.setColor(color);
			g.fillRect(x, (int)(getHeight()*0.90) - height, width, height);
			g.setColor(Color.black);
			g.drawRect(x, (int)(getHeight()*0.90) - height, width, height);
			x += (width + 2);
		}
         g.drawString("Payments", (int)(getWidth()*0.80),(int)(getHeight()*0.95));
        /*
        AffineTransform at = new AffineTransform();
          Graphics2D g2d = (Graphics2D)g;

                     at.setToRotation(-Math.PI/2.0,this.getWidth()/2.0, this.getHeight()/2.0);
        g2d.setTransform(at);

        */
                g.drawString("Principal", (int) (10),(int)( 50));

      //  g.clearRect(0,0,this.getWidth(),this.getHeight());
	}

//	@Override
	public Dimension getPreferredSize() {
		return new Dimension(aa.size() * 10 + 2, 50);
	}

	public static void main(String[] args)
	{
		JFrame frame = new JFrame("Bar Chart");
		BarChart chart = new BarChart();
		chart.addBar(Color.red, 100);
		chart.addBar(Color.green, 8);
		chart.addBar(Color.blue, 54);
		chart.addBar(Color.black, 23);
		frame.getContentPane().add(chart);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America 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
Avatar of zomrob

ASKER

Awesome, yan you rock. Thanks for all your help.