Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Calculate Button Not Working

  1. #1
    Junior Member
    Join Date
    Sep 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Calculate Button Not Working

    Hello, I am new to java and for a school project due Monday, I have to create a program that calculates the mortgage and displays each months payments in a table below the reset and calculate buttons. My problem is that I cannot get the calculate button to work and I have no idea what is wrong as eclipse only brings up an error when the calculate button is pressed. Here is my code, thanks for helping me with this. By the way, I apologize about it being messy.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
     
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
     
    public class JamesProctorProgramGUIWk3 extends JFrame implements ActionListener{
     
     
    /**
    	 * 
    	 */
    private static final long serialVersionUID = 1L;
     
    //Loan Values
    double principalPaid; 
    double currentInter;
    double balanceAmount;
    double monthPrincipal; 
    double interestRate;	
    double paymentField;  
    double monthInterest; 
    double[] interRate = {0.0535, 0.0550, 0.0575}; 
    int[] yearRate = {7, 15, 30}; 
    int termYears, termMonths, i = 0, m = 0, done;
    int monthAmount; 
    String[] rate = {"7 year at 5.35%", "15 year at 5.5%", "30 year at 5.75%"};
    String principalAmount;
     
    //text fields
    JTextField loanField = new JTextField("", 7);  
    JTextField monthField = new JTextField("", 7); 
     
     
     
    //creates the panel
    JPanel contentPanel;
     
    //creates the reset and calculate buttons
    JButton calculateButton, resetButton;
     
    //creates labels
    JLabel loanAmountlbl, monthlyPaymentlbl;
     
    //Sets Decimal Format
    DecimalFormat paymentFormat = new DecimalFormat ("$###,##0.00");;
     
    //create combo box
    JComboBox percentBox = new JComboBox();
     
    //creates table format
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
     
    //creates GUI
    public JamesProctorProgramGUIWk3()
    {
    	super();
    	createGUI();
    }
    	public void createGUI()
    	{
    		this.setSize(700, 300); //length, height
    		this.setLocation(0, 0); //this specifies where the frame position will be on the screen
    		this.setContentPane(contentPanel());
    		this.setTitle("James Proctor Program GUI Wk3");
    	}
        public JPanel contentPanel()
        {
        	contentPanel = new JPanel();
            contentPanel.setLayout(null);
     
            //adds labels to the panel
            loanAmountlbl = new JLabel("Mortgage:");
            loanAmountlbl.setLocation(200, 30);
            loanAmountlbl.setSize(100, 25);
            contentPanel.add(loanAmountlbl);
     
            monthlyPaymentlbl = new JLabel("Monthly Payment:");
            monthlyPaymentlbl.setLocation(158, 85);
            monthlyPaymentlbl.setSize(100, 30);
            contentPanel.add(monthlyPaymentlbl);
     
     
            //adds text fields
            loanField = new JTextField("", 10);
            loanField.setLocation(280, 30);
            loanField.setSize(150, 25);
            contentPanel.add(loanField);
     
            monthField = new JTextField("", 10);
            monthField.setLocation(280, 85);
            monthField.setSize(150, 25);
            contentPanel.add(monthField);
     
            //this adds the combo box and action listener
            percentBox.addItem(rate[0]);
            percentBox.addItem(rate[1]);
            percentBox.addItem(rate[2]);
            percentBox.setLocation(280, 55);
            percentBox.setSize(150, 25);
            percentBox.addActionListener(this);
            contentPanel.add(percentBox);
     
            //adds a scrollbar
            JScrollPane scroller = new JScrollPane(table);
            contentPanel.add(scroller);
            scroller.setSize(650,300);
            scroller.setLocation(20, 150);
     
            //adds column names to the table
            model.addColumn("Payment Number");
            model.addColumn("Current Interest");
            model.addColumn("Principal Paid");
            model.addColumn("New Balance");
     
     
            //setup up buttons
            resetButton = new JButton("Reset");
            resetButton.setLocation(450, 55);
            resetButton.setSize(100, 25);
            contentPanel.add(resetButton);
     
     
            calculateButton = new JButton("Calculate");
            calculateButton.setLocation(450, 85);
            calculateButton.setSize(100, 25);
            contentPanel.add(calculateButton);
     
     
            calculateButton.addActionListener(this);
            resetButton.addActionListener(this);
            return contentPanel;
        }
     
        //action event for the calculate button
        public void actionPerformed(ActionEvent e)
        {
     
                String calculate = e.getActionCommand();
                if (e.getSource() == percentBox) {
                	switch (percentBox.getSelectedIndex()){
                case 0:
                        i = 0;
                        break;
                case 1:
                        i = 1;
                        break;
                case 2:
                        i = 2;
                        break;
                }
            }
                if (calculate == "Calculate")
                {
                	loanField.setText("");
                	principalAmount = monthField.getText();
     
                	//cannot get the calculate button to function 
                	//error has to do with the below line of code
                		monthPrincipal = Double.parseDouble(principalAmount);
                }
                if(done == 1)
                        done = 0;
                else {
                                interestRate = interRate[i];
     
                                termYears = yearRate[i];
     
                                monthInterest = interestRate/(12*100); //finds the monthly interest
     
                                termMonths = termYears*12; //calculates term length in months
     
                                paymentField = monthInterest*monthPrincipal/(1-Math.pow((1+monthInterest), -termMonths)); //calculates monthly payment
     
                                loanField.setText(" " + paymentFormat.format(paymentField));
     
                                //loop for the table to display each payment
                                for (m = 0; m <= monthAmount; m ++) {
     
                                	monthAmount = yearRate[i]*12;
     
                                	currentInter = monthPrincipal * monthInterest;
     
                                	principalPaid = paymentField - currentInter;
     
                                	balanceAmount = monthPrincipal - principalPaid;
     
                                	monthPrincipal = balanceAmount;
     
                                    if(monthPrincipal <= 1){ break;}
     
                                	model.addRow(new Object[]{m+1, paymentFormat.format(currentInter), paymentFormat.format(principalPaid), paymentFormat.format(balanceAmount)});
     
                                    if(monthPrincipal <= 1){ break;}
     
                }
                }
                //action event for the reset button
                //this button does work
                if (e.getSource() == resetButton)
                {
                    loanField.setText(""); 
                    monthField.setText(""); 
                    loanField.requestFocusInWindow(); 
                    percentBox.setSelectedIndex(0);
     
                    model.setRowCount(0);
                }
        }
     
                //shows the GUI
    public static void main(String[] args){
    	new JamesProctorProgramGUIWk3().setVisible(true);
    	}
    }


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Calculate Button Not Working

    Quote Originally Posted by czerenborg View Post
    eclipse only brings up an error when the calculate button is pressed.
    We don't read minds. Copy and paste the error message here.
    Improving the world one idiot at a time!

  3. #3
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Calculate Button Not Working

    Copy and paste the error message here.
    ... and tell us which line in your source the line numbers in the error message refer to.

    for a school project due Monday
    You're asking a question whole days before your assignment is due? I think you must be the best student to ever post a question here

  4. #4
    Junior Member
    Join Date
    Sep 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calculate Button Not Working

    Here is the error:

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String

    I fixed this error with a try and catch, but now the button does not calculate anything. It just places 0.00 as the answer, and it does not display anything in the table.
    Do you need the entire source again or just the section pertaining to the try and catch and the calculations?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Calculate Button Not Working

    That looks like only part of the message. The rest of the message has the source code line number where the error occured.

    Did the error occur on statement that was trying to convert a String to a number and the String was empty? You need to add code to test if the String is empty BEFORE trying to convert it to a number.
    If the String is empty, don't try to convert it. Hint: use an if test

    Otherwise post the code where the error occurred.

  6. #6
    Junior Member
    Join Date
    Sep 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calculate Button Not Working

    I have it now where the Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String, error no longer pops up. However, no matter the number I place in the loanField text field, the code I use for the exception happens. I am thinking that the reason has to do with the code from line 164 to 197, as that is the exception handler and calculation part of the code.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
     
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
     
    public class JamesProctorGUIWk3 extends JFrame implements ActionListener{
     
     
    /**
    	 * 
    	 */
    private static final long serialVersionUID = 1L;
     
    //Loan Values
    double principalPaid; 
    double currentInter;
    double balanceAmount;
    double monthPrincipal; 
    double interestRate;	
    double paymentField;  
    double monthInterest; 
    double[] interRate = {0.0535, 0.0550, 0.0575}; 
    int[] yearRate = {7, 15, 30}; 
    int termYears, termMonths, i = 0, m = 0, done;
    int monthAmount; 
    String[] rate = {"7 year at 5.35%", "15 year at 5.5%", "30 year at 5.75%"};
    String principalAmount;
     
    //text fields
    JTextField loanField = new JTextField("", 7);  
    JTextField monthField = new JTextField("", 7); 
     
    //java.lang.NumberFormatException
     
    //creates the panel
    JPanel contentPanel;
     
    //creates the reset and calculate buttons
    JButton calculateButton, resetButton;
     
    //creates labels
    JLabel loanAmountlbl, monthlyPaymentlbl;
     
    //Sets Decimal Format
    DecimalFormat paymentFormat = new DecimalFormat ("$###,##0.00");;
     
    //create combo box
    JComboBox percentBox = new JComboBox();
     
    //creates table format
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
     
    //creates GUI
    public JamesProctorGUIWk3()
    {
    	super();
    	createGUI();
    }
    	public void createGUI()
    	{
    		this.setSize(700, 300); //length, height
    		this.setLocation(0, 0); //this specifies where the frame position will be on the screen
    		this.setContentPane(contentPanel());
    		this.setTitle("James Proctor Program GUI Wk3");
    	}
        public JPanel contentPanel()
        {
        	contentPanel = new JPanel();
            contentPanel.setLayout(null);
     
            //adds labels to the panel
            loanAmountlbl = new JLabel("Mortgage:");
            loanAmountlbl.setLocation(200, 30);
            loanAmountlbl.setSize(100, 25);
            contentPanel.add(loanAmountlbl);
     
            monthlyPaymentlbl = new JLabel("Monthly Payment:");
            monthlyPaymentlbl.setLocation(158, 85);
            monthlyPaymentlbl.setSize(100, 30);
     
            contentPanel.add(monthlyPaymentlbl);
     
     
            //adds text fields
            loanField = new JTextField("", 10);
            loanField.setLocation(280, 30);
            loanField.setSize(150, 25);
            contentPanel.add(loanField);
     
            monthField = new JTextField("", 10);
            monthField.setLocation(280, 85);
            monthField.setSize(150, 25);
           // monthField.setEditable(false);
            contentPanel.add(monthField);
     
            //this adds the combo box and action listener
            percentBox.addItem(rate[0]);
            percentBox.addItem(rate[1]);
            percentBox.addItem(rate[2]);
            percentBox.setLocation(280, 55);
            percentBox.setSize(150, 25);
            percentBox.addActionListener(this);
            contentPanel.add(percentBox);
     
            //adds a scrollbar
            JScrollPane scroller = new JScrollPane(table);
            contentPanel.add(scroller);
            scroller.setSize(650,300);
            scroller.setLocation(20, 150);
     
            //adds column names to the table
            model.addColumn("Payment");
            model.addColumn("Interest");
            model.addColumn("Principal");
            model.addColumn("Balance");
     
     
            //setup up buttons
            resetButton = new JButton("Reset");
            resetButton.setLocation(450, 55);
            resetButton.setSize(100, 25);
            contentPanel.add(resetButton);
     
     
            calculateButton = new JButton("Calculate");
            calculateButton.setLocation(450, 85);
            calculateButton.setSize(100, 25);
            contentPanel.add(calculateButton);
     
     
            calculateButton.addActionListener(this);
            resetButton.addActionListener(this);
            return contentPanel;
        }
     
        //action event for the calculate button
        public void actionPerformed(ActionEvent e)
        {
     
                String calculate = e.getActionCommand();
                if (e.getSource() == percentBox) {
                	switch (percentBox.getSelectedIndex()){
                case 0:
                        i = 0;
                        break;
                case 1:
                        i = 1;
                        break;
                case 2:
                        i = 2;
                        break;
                }
            }
                if (calculate == "Calculate")
                {
                	loanField.setText("");
                	principalAmount = monthField.getText();
     
                	try
                	{
                		monthPrincipal = Double.parseDouble(principalAmount);
                		if (monthPrincipal <= 0) throw new NumberFormatException();
                	}
     
                	catch (NumberFormatException a){
                		monthField.setText("Number must be greater than 0");
                	}}{
     
     
                                //loop for the table to display each payment
                                for (m = 0; m <= monthAmount; m ++) {
     
                                	monthAmount = yearRate[i]*12;
     
                                	currentInter = monthPrincipal * monthInterest;
     
                                	principalPaid = paymentField - currentInter;
     
                                	balanceAmount = monthPrincipal - principalPaid;
     
                                	monthPrincipal = balanceAmount;
     
                                    if(monthPrincipal <= 1){ break;}
     
                                	model.addRow(new Object[]{m+1, paymentFormat.format(currentInter), paymentFormat.format(principalPaid), paymentFormat.format(balanceAmount)});
     
                                    if(monthPrincipal <= 1){ break;}
     
                }
     
                //action event for the reset button
                //this button does work
                if (e.getSource() == resetButton)
                {
                    loanField.setText(""); 
                    monthField.setText(""); 
                    loanField.requestFocusInWindow(); 
                    percentBox.setSelectedIndex(0);
     
                    model.setRowCount(0);
                }}}
     
     
     
    			//shows the GUI
    public static void main(String[] args){
    	new JamesProctorGUIWk3().setVisible(true);
    	}
    }

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Calculate Button Not Working

    If you get errors please copy and paste the full text of the message here.

    You should check if principalAmount is empty BEFORE trying to convert it.

    Your throwing and catching the NumberFormatException in the next statement is silly. Why not just print out the message when you detect the error?

  8. #8
    Junior Member
    Join Date
    Sep 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calculate Button Not Working

    I finally figured it out. I had the loanField and monthField variables mixed up. For the heck of it, I decided to enter a number into the monthly payment text field instead of the mortgage field and it worked as intended with no errors.

  9. #9
    Junior Member
    Join Date
    Sep 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calculate Button Not Working

    This thread is solved, but there is no option in the thread menu for me to mark it as such. Is there another way?

Similar Threads

  1. I trying to calculate total price.
    By Muhanguzi in forum JDBC & Databases
    Replies: 6
    Last Post: June 15th, 2011, 03:35 PM
  2. GUI - calculate BMI (need help asap)
    By jahead in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 18th, 2011, 04:10 AM
  3. My Clear Info button is not working with Screenshot
    By drkossa in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 15th, 2010, 08:06 AM
  4. Calculate primes help
    By TommyFiz in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 27th, 2009, 11:41 PM
  5. Replies: 4
    Last Post: January 27th, 2009, 12:03 AM