Java Netbeans database calculation help

Hi,

I have my netbeans database I created, and used the wizard to create a GUI interface. ALL is totally well in that area (surprising to me LOL). I would like to add a button that will perform a calculation of three cells with the pressing of a calculate button. (Similar to excel calculations). Are there any tutorials out there that help explain how to do this?

Thank you!!

marchbabyAsked:
Who is Participating?
 
objectsCommented:
the following shows you how to multiply the contents of two text fields (tfa and tfb) and store the result in another text filed (tfc)

button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent event) {
       int a = Integer.parseInt(tfa.getText());
       int b = Integer.parseInt(tfb.getText());
       int c = a * b;
       tfc.setText(Integer.toString(c));
   }
});

You can adjust that to meet your needs
let me know if you have any questions
0
 
for_yanCommented:
Maybe your wizard to create GUI interface will allow you to add the button?

Or maybe you want to post your code, so that we could look at it and give some suggestions
0
 
marchbabyAuthor Commented:
I have added the button, I even have the calculation script, just not sure where to put it. I have alot of code, should I post it all?
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
marchbabyAuthor Commented:
Savant,

Do I put that code in the custom code area of the button? (after adjusted of course)
0
 
for_yanCommented:
Can you associate the button with the ActionListener in the wizard?
The code is waht is executed upon ActionEvent on that button
0
 
marchbabyAuthor Commented:
Actually my calculation script looks like this:

monthlypayment = (loanamount * (interestrate / (1 -
            Math.pow(1 + interestrate, termyears * -1))));
        monthlypayment = Math.ceil(monthlypayment * 100) / 100;

0
 
for_yanCommented:
That is fine - you should also read these values from the textfileds
probably where user puts them and make numbers from user input (strings)
All this whould be within that actionPerformed(ActionEvent ae)
method which should be associated with the button
0
 
objectsCommented:
> Do I put that code in the custom code area of the button? (after adjusted of course)

I think so (depending on what your calling the custom area)
or in your buttons action listener if you already have one

> Actually my calculation script looks like this:

Thats fine just replace the calculation with your own

Points is to do it in the buttons action listener
0
 
for_yanCommented:
Are you writing MortgageCalculator ?
0
 
marchbabyAuthor Commented:
Yan,

Yea, the calculate button is my only hiccup
0
 
objectsCommented:
Its the same as you did previously in onCalcButtonClick() which gets called by your action listener


import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


public class Main implements Runnable {
    //The main container for this application
    public JFrame jfrMain;
    public JTextField fnameTextField;
    public JTextField lnameTextField;
    public JTextField phoneTextField;
    public JTextField loanAmountField;
    public JTextField termYearsField;
    public JTextField interestRateField;
    public JTextField monthlyPaymentField;
    public JButton calcButton;
    public JButton nextButton;
    public JButton exitButton;

    /**
     *
     * @param args Command line arguments (not used)
     */
    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Main());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * Setup the GUI and start the program.
     */
    public void run() {
        jfrMain = new JFrame("Mortgage Calculator");
        jfrMain.setLayout(new GridLayout(5, 2));
        jfrMain.setSize(new Dimension(500, 700));

        //Construct the fields
        fnameTextField = new JTextField(20);
        lnameTextField = new JTextField(20);
        phoneTextField = new JTextField(20);
        loanAmountField = new JTextField(10);
        termYearsField = new JTextField(4);
        interestRateField = new JTextField(2);
        monthlyPaymentField = new JTextField(10);
        monthlyPaymentField.setEditable(false);

        //adding the labels
        jfrMain.add(new JLabel("First Name"));
        jfrMain.add(fnameTextField);
        jfrMain.add(new JLabel("Last Name"));
        jfrMain.add(lnameTextField);
        jfrMain.add(new JLabel("Phone"));
        jfrMain.add(phoneTextField);
        jfrMain.add(new JLabel("Loan Amount"));
        jfrMain.add(loanAmountField);
        jfrMain.add(new JLabel(" Loan Terms in months"));
        jfrMain.add(termYearsField);
        jfrMain.add(new JLabel("Interest Rate"));
        jfrMain.add(interestRateField);
        jfrMain.add(new JLabel("Monthly payment"));
        jfrMain.add(monthlyPaymentField);

        //calculate button
        calcButton = new JButton("Calculate");
        calcButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    onCalcButtonClick(e);
                }
            });

        jfrMain.add(calcButton);
        jfrMain.setVisible(true);

        // next button (still workiing on it)
        nextButton = new JButton("Next");
        nextButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    nextButton.setActionCommand("Next");
                }
            });
        jfrMain.add(nextButton);
        jfrMain.setVisible(true);

        //exit button still working on
        //exitButton = new JButton ("Exit");
        //exitButton.addActionListener (new ActionListener() {
        //public void actionPerformed(ActionEvent e)
        //    {
        //     System.exit(0);
        //       }
        //      });
        // jfrMain.add(exitButton);
        // jfrMain.setVisible(true);
    }

    public void onCalcButtonClick(ActionEvent e) {
        double loanAmount;
        double termYears;
        double interestRate;

        try {
            loanAmount = Double.parseDouble(loanAmountField.getText());
        } catch (NumberFormatException nf) {
            JOptionPane.showMessageDialog(jfrMain, "Please enter loan amount");

            return;
        }

        try {
            termYears = Double.parseDouble(termYearsField.getText());
        } catch (NumberFormatException nf) {
            JOptionPane.showMessageDialog(jfrMain,
                "Please enter mortgage term length");

            return;
        }

        try {
            interestRate = Double.parseDouble(interestRateField.getText()) / 100;
        } catch (NumberFormatException nf) {
            JOptionPane.showMessageDialog(jfrMain, "Please enter interest rate");

            return;
        }

        //Calculate monthly payment 
        double payment = calculatePayment(loanAmount, termYears, interestRate);
        monthlyPaymentField.setText(new Double(payment).toString());
    }

    public double calculatePayment(double loanAmount, double termYears,
        double interestRate) {
        double monthlyInterest = interestRate / 12;
        double monthlyPayment = (double) (loanAmount * (monthlyInterest / (1 -
            Math.pow(1 + monthlyInterest, termYears * -1))));
        monthlyPayment = Math.ceil(monthlyPayment * 100) / 100;

        return monthlyPayment;
    }
}

Open in new window

0
 
for_yanCommented:
OK, try to find how to make connection to ActionListener
0
 
for_yanCommented:
Look at this mortgage calculator

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

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


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

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




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

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static String [] toReplace;
         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

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

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

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

     // Declaration of variables

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


     //This is the class constructor - initialize the components

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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


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




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

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

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

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

                    //Calculates the monthly payment for mortgage
                    monthly_payment = (principal* monthly_interest_rate)/(1 - Math.pow(1 + monthly_interest_rate, -number_of_months));


                   // Sets the result text
                    result.setText("Loan Amount = " + money.format(principal)
                    +"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
                    + Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

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

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

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

        return contentPanel;
    }




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

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

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

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

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

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

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

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

    }

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

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

VeryMortgageCalculator.PNG
0
 
marchbabyAuthor Commented:
exactly LOL!

This is how my button reads now:

calcButton.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        calcButtonMouseClicked(evt);
    }
});

Should I then add:
public void onCalcButtonClick(ActionEvent e){
monthlypayment = (loanamount * (interestrate / (1 -
            Math.pow(1 + interestrate, termyears * -1))));
        monthlypayment = Math.ceil(monthlypayment * 100) / 100;

return monthlypayment;
}

0
 
for_yanCommented:
No you can put your code for calculation inside
 calcButtonMouseClicked(evt);
0
 
marchbabyAuthor Commented:
Sage! That's awesome!! I have to add first name, last name and phone. I don't need the amortization schedule though. The upcoming weeks of course add more functions which is why I switched to the database. I just can't figure it out with an array.
0
 
for_yanCommented:
You start from raeding your values from textfields or from those components where user placed them
and then do the calculation
0
 
for_yanCommented:
You can modify it any way you want.
And remove this output of payments per month
, but connections to buttons and action listneers still follow the same mechanism
0
 
objectsCommented:
See the onCalcButtonClick() code that I posted above. It does exactly what you need
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.