hello, I'm a beginner and I'm trying to create a mortgage GUI and I'm having some trouble trying to figure out why the variables in my ActionListener are not read. can someone assist? here is my code:

import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.*;


/**
 * This is code based on the layout design created by David Lilley
 * POS 407 student January 2006. He wanted this layout and could not
 * achieve it as he wanted. I wrote the code to show him how to do it in
 * return for me using the code as an example for future classes. I hope you
 * enjoy.
 * @author Chip Dickson
 */
public class LayoutExample1 extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 4364582253350924044L;

    private Container jContentPane = null;
    private JSplitPane splitpane = null;
    private JPanel leftpanel = null;
    private JScrollPane rightpane = null;
    private JTextArea amortization_out = null;
    private JRadioButton option1 = null;
    private JRadioButton option2 = null;
    private JRadioButton option3 = null;
    private ButtonGroup btgroup_options;
    private ButtonGroup btgroup_plans;
    private JLabel lb_terms = null;
    private JTextField tf_terms = null;
    private JLabel lb_interest = null;
    private JTextField tf_interest = null;
    private JLabel lb_principal = null;
    private JTextField tf_principal = null;
    private JButton calc_button = null;
    private JButton clear_button = null;  // me
    private JButton exit_button = null;

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

    private void initialize()
    {
        // set up the basics
        jContentPane = this.getContentPane();
        setTitle("Mcbride Financial Services Mortgage Calculator");   // I changed title
        setSize(600, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Notice the top pane is just a simple BoxLayout
        jContentPane.setLayout(new BoxLayout(jContentPane, BoxLayout.Y_AXIS));
        // create a splitpane to layout out code
        splitpane = new JSplitPane();
        splitpane.setDividerSize(2);
        splitpane.setDividerLocation(300); // set the divider right in the middle
        //splitpane.setEnabled(false); // locks the divider bar
        // Call the method to load the left side of the split pane
        loadLeftSide();
        // load the right side of the split pane
        loadRightSide();
        // add the split pane to the content pane
        jContentPane.add(splitpane, null);
    }

    /**
     *
     */
    private void loadRightSide()
    {
        // Not much to the right side... just a JScrollPane and the textArea to go in it...
        rightpane = new JScrollPane();
        // make the scroll bars always be there
        rightpane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        rightpane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        // give ourselves a nice boarder
        rightpane.setViewportBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        amortization_out = new JTextArea();
        Font displayFont = new Font("Serif", Font.BOLD, 14);

        // don't want folks typing in here... so we better not let them.
        amortization_out.setEditable(false);
        amortization_out.setFont(displayFont);
        amortization_out.setText("");

        rightpane.setViewportView(amortization_out);
        splitpane.setRightComponent(rightpane);
    }

    /**
     *
     */
    private void loadLeftSide()
    {
        leftpanel = new JPanel();
        leftpanel.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
        // add a nice boarder to the panel
        leftpanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.SoftBevelBorder.LOWERED));
        //       we are using a grid bag layout for this...
        leftpanel.setLayout(new GridBagLayout());
        // we want 2 button groups (one on top, one on the bottom)
        // this is how you make your radio buttons turn off when another is clicked on
        btgroup_options = new ButtonGroup();
        btgroup_plans = new ButtonGroup();

        // GridBagLayout Base constraints
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 0);
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 0;
        gridBagConstraints.ipady = 0;
        gridBagConstraints.gridx = 0;
        // Create all our components
        option1 = new JRadioButton("Option 1");
        option2 = new JRadioButton("Option 2");
        option3 = new JRadioButton("Option 3");
        // put the buttons in a group
        btgroup_options.add(option1);
        option1.setSelected(true); // sets the default button on
        option1.setActionCommand("1");   // me
        option2.setActionCommand("2");   // me
        option3.setActionCommand("3");   // me
        btgroup_options.add(option2);

        btgroup_options.add(option3);
        lb_terms = new JLabel("Terms");
        lb_interest = new JLabel("Interest");
        lb_principal = new JLabel("Principal");
        tf_terms = new JTextField();
        // limits the number of characters to 4, just to demo it.. no functional reason :).
        tf_terms.setDocument(new JTextFieldLimit(4)); // JTextFieldLimit is an inner class defined at teh bottom of this file.
        tf_interest = new JTextField();
        tf_principal = new JTextField();
        calc_button = new JButton("Calculate");
        // add the action listener
        calc_button.addActionListener(this);
        clear_button = new JButton("Clear");  // me
        // add the clear action command         me
        clear_button.setActionCommand ("Clear");// me
        exit_button = new JButton("Exit");
        // add the action listener
        exit_button.addActionListener(this);
        // lay the components out
        // all of these are on the first row (y=0)
        leftpanel.add(option1, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        leftpanel.add(option2, gridBagConstraints);
        gridBagConstraints.gridx = 2;
        leftpanel.add(option3, gridBagConstraints);
        // **** Second row
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        leftpanel.add(lb_terms, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        // we want the text fields to go across 2 cells
        gridBagConstraints.gridwidth = 2;
        // ... and we want it to fill the space
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        leftpanel.add(tf_terms, gridBagConstraints);
        // set everything back to default
        gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
        gridBagConstraints.gridwidth = 1;
        //  **** Third row
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        leftpanel.add(lb_interest, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        // we want the text fields to go across 2 cells
        gridBagConstraints.gridwidth = 2;
        // ... and we want it to fill the space
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        leftpanel.add(tf_interest, gridBagConstraints);
        // set everything back to default
        gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
        gridBagConstraints.gridwidth = 1;
        //  **** Fourth row
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        leftpanel.add(lb_principal, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        // we want the text fields to go across 2 cells
        gridBagConstraints.gridwidth = 2;
        // ... and we want it to fill the space
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        leftpanel.add(tf_principal, gridBagConstraints);
        // set everything back to default
        gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
        gridBagConstraints.gridwidth = 1;
        // **** Fith Row
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        // Buttons are sort of funny, so we have to do a little extra work to get them to look right
        // in this layout. I will create individual contraints for each... you could create constrains
        // for every component, and in a more sophisticated layout, you probably would.
        // **** Sixth row
        GridBagConstraints calc_constraints = new GridBagConstraints();
        calc_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
        calc_constraints.gridy = 5;
        calc_constraints.ipadx = 13;
        calc_constraints.ipady = 11;
        calc_constraints.gridx = 0;
        leftpanel.add(calc_button, calc_constraints);
        GridBagConstraints clear_constraints = new GridBagConstraints();// me
        clear_constraints.insets = new java.awt.Insets(0, 0, 0, 0);     //me
        clear_constraints.gridy = 5;                                     //me
        clear_constraints.ipadx = 27;                                     //me
        clear_constraints.ipady = 11;                                    //me
        clear_constraints.gridx = 1;                                     // me
        leftpanel.add(clear_button, clear_constraints);                 // me
        GridBagConstraints exit_constraints = new GridBagConstraints();
        exit_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
        exit_constraints.gridy = 5;
        exit_constraints.ipadx = 40;
        exit_constraints.ipady = 11;
        exit_constraints.gridx = 2;
        leftpanel.add(exit_button, exit_constraints);

        // put the left hand side in the split pane
        splitpane.setLeftComponent(leftpanel);

        ActionListener EraseFieldsListener = new EraseFieldsListener();  // sets clear listener  me
        clear_button.addActionListener(EraseFieldsListener);             // me
        clear_button.addActionListener(this);                            // me


    }

    RadioListener myListener = new RadioListener();     // me
    {
        option1.addActionListener(myListener);  
        option2.addActionListener(myListener);
        option3.addActionListener(myListener);  

    }

    class RadioListener implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {

            if (evt.getActionCommand() == "1")
            {
                tf_terms.setText("7");
                tf_interest.setText("5.35");
            }
            if (evt.getActionCommand() == "2")
            {
                tf_terms.setText("15");
                tf_interest.setText("5.50");
            }
            if (evt.getActionCommand() == "3")
            {
                tf_terms.setText("30");
                tf_interest.setText("5.75");
            }

        }

    }

    /* (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */



     // me
     public class EraseFieldsListener implements ActionListener          // listener class for the clear button
     {
         public void actionPerformed(ActionEvent ev)
         {
             Object source = ev.getSource();
             if (source == clear_button)
             {
                 tf_terms.setText("");                          // clears the loan amount field
                 tf_interest.setText("");                            // clears the term field
                 tf_principal.setText("");                            // clears the payment field
                 amortization_out.setText("");
             }
         }
     }


    Calculator calculator = new Calculator();  // call our MortgageCalc class 

    public void actionPerformed(ActionEvent e)
        {

            Object source = e.getSource();
            if (source == exit_button)
            {
                System.exit(0);
            }

            else
                source = e.getSource();
            if (source == calc_button)
            {
                try
            {
                double principal = Double.parseDouble(tf_principal.getText()); // problem is here
                double rate = Double.parseDouble(tf_interest.getText());  // and here
                int terms = Integer.parseInt(tf_terms.getText());   // and here
            }
            catch (NumberFormatException nfe)
            {
                // Tell the user about the error...
                JOptionPane.showMessageDialog(null, "Please make sure all your entries are numeric!", "USER INPUT ERROR", JOptionPane.ERROR_MESSAGE);
            }


        }
        }


    /**
     * Inner class to limit the size of a text field.
     * Could be in a seperate file, but since we are only using it for this class, it should be here.
     *
     * NOTE: This is not the same as defining 2 classes in the same file. This class is part of the top class
     * That is why it is consided an inner class. Other than this type of thing, you have no reason to have
     * an inner class in your work.
     *
     * Also, if you want to limit the input of a text field in your code, feel free to copy this as is and use it.
     */
    public class JTextFieldLimit extends PlainDocument
    {
        private static final long serialVersionUID = -349808007443039827L;
        private int limit;
        // optional uppercase conversion
        private boolean toUppercase = false;

        JTextFieldLimit(int limit)
        {
            super();
            this.limit = limit;
        }
        /**
         * Sets the limit, and if you pass in true here.. will force the
         * input to upper case before displaying it.
         * @param limit
         * @param upper
         */
        JTextFieldLimit(int limit, boolean upper)
        {
            super();
            this.limit = limit;
            toUppercase = upper;
        }
        /**
         * This is a callback method used by Java when text is entered into a text field. This is the
         * place we can check the length before we actually place the character in the GUI.
         */
        public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException
        {
            if (str == null)
                return;

            if ((getLength() + str.length()) <= limit)
            {
                if (toUppercase)
                    str = str.toUpperCase();
                super.insertString(offset, str, attr);
            }
        }
    }



    /**
     * MAIN... the entry point to this program
     * @param args
     */
    public static void main(String[] args)
    {
            LayoutExample1 example = new LayoutExample1();
            example.setVisible(true);

    }

    public class Calculator
    {

        Double s;
        Double MPayAmt;
        Double Amount = Double.parseDouble(tf_principal.getText()); // retrieves the loan amount
        Double Term = Double.parseDouble(tf_terms.getText());     // retrieves the loan terms
        Double rate = Double.parseDouble(tf_interest.getText());{      // retrieves the inputed interest rate
        rate = rate /100/12;  // is the monthly interest rate calculation
        s = 1 + rate;         // this is adding one onto r to effectively calculate Math.pow
        Term = Term * 12;     // this converts terms into months
        MPayAmt = (rate / (1 - Math.pow(s, -Term))) * Amount;   // calculates payment, formula retrieved from [url]http://www.financialone.com/mortgages/mortcalcs[/url]
        DecimalFormat numFormatter = new DecimalFormat("#,##0.00"); // formats the decimal output
        String MPaymentFmt = numFormatter.format(MPayAmt);
        amortization_out.setText("Your monthly payment is $" + MPaymentFmt);
        }

    }
    //  cannot put closing curly brace ??

}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

One, who wrote this code? Is it yours? Two, what exactly is the problem? We need a more specific question. Point us to the section of the code to look at it. Three, repost in code tags with formatting/indentation:

[code=JAVA] // paste code here

[/code]

One, who wrote this code? Is it yours? Two, what exactly is the problem? We need a more specific question. Point us to the section of the code to look at it. Three, repost in code tags with formatting/indentation:[/noparse]

one = the code is a combination of my facilitator (main GUI) and me (calculations, exception handlers, radio buttons, display of output and clear button)
two = the problem I am experiencing is I cannot get my exception or my exit button to work properly, - cannot figure out why the variables are not read. The problem is located in the ActionListener right below my RadioListener. Thanks for helping I've just got jsut about everything working in there except for the catch numbers exception and the exit button.

[code=JAVA] // import java.awt.Container; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat;

import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.text.*;

/** * This is code based on the layout design created by David Lilley * POS 407 student January 2006. He wanted this layout and could not * achieve it as he wanted. I wrote the code to show him how to do it in * return for me using the code as an example for future classes. I hope you * enjoy. * @author Chip Dickson */ public class LayoutExample1 extends JFrame implements ActionListener { private static final long serialVersionUID = 4364582253350924044L;

private Container jContentPane = null; private JSplitPane splitpane = null; private JPanel leftpanel = null; private JScrollPane rightpane = null; private JTextArea amortization_out = null; private JRadioButton option1 = null; private JRadioButton option2 = null; private JRadioButton option3 = null; private ButtonGroup btgroup_options; private ButtonGroup btgroup_plans; private JLabel lb_terms = null; private JTextField tf_terms = null; private JLabel lb_interest = null; private JTextField tf_interest = null; private JLabel lb_principal = null; private JTextField tf_principal = null; private JButton calc_button = null; private JButton clear_button = null; // me private JButton exit_button = null;

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

private void initialize() { // set up the basics jContentPane = this.getContentPane(); setTitle("Mcbride Financial Services Mortgage Calculator"); // I changed title setSize(600, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Notice the top pane is just a simple BoxLayout jContentPane.setLayout(new BoxLayout(jContentPane, BoxLayout.Y_AXIS)); // create a splitpane to layout out code splitpane = new JSplitPane(); splitpane.setDividerSize(2); splitpane.setDividerLocation(300); // set the divider right in the middle //splitpane.setEnabled(false); // locks the divider bar // Call the method to load the left side of the split pane loadLeftSide(); // load the right side of the split pane loadRightSide(); // add the split pane to the content pane jContentPane.add(splitpane, null); }

/** * */ private void loadRightSide() { // Not much to the right side... just a JScrollPane and the textArea to go in it... rightpane = new JScrollPane(); // make the scroll bars always be there rightpane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); rightpane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // give ourselves a nice boarder rightpane.setViewportBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); amortization_out = new JTextArea(); Font displayFont = new Font("Serif", Font.BOLD, 14);

// don't want folks typing in here... so we better not let them. amortization_out.setEditable(false); amortization_out.setFont(displayFont); amortization_out.setText("");

rightpane.setViewportView(amortization_out); splitpane.setRightComponent(rightpane); }

/** * */ private void loadLeftSide() { leftpanel = new JPanel(); leftpanel.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT); // add a nice boarder to the panel leftpanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.SoftBevelBorder.LOWERED)); // we are using a grid bag layout for this... leftpanel.setLayout(new GridBagLayout()); // we want 2 button groups (one on top, one on the bottom) // this is how you make your radio buttons turn off when another is clicked on btgroup_options = new ButtonGroup(); btgroup_plans = new ButtonGroup();

// GridBagLayout Base constraints GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 0); gridBagConstraints.gridy = 0; gridBagConstraints.ipadx = 0; gridBagConstraints.ipady = 0; gridBagConstraints.gridx = 0; // Create all our components option1 = new JRadioButton("Option 1"); option2 = new JRadioButton("Option 2"); option3 = new JRadioButton("Option 3"); // put the buttons in a group btgroup_options.add(option1); option1.setSelected(false); // sets the default button on option1.setActionCommand("1"); // me option2.setActionCommand("2"); // me option3.setActionCommand("3"); // me btgroup_options.add(option2); btgroup_options.add(option3); lb_terms = new JLabel("Terms"); lb_interest = new JLabel("Interest"); lb_principal = new JLabel("Principal"); tf_terms = new JTextField(); // limits the number of characters to 4, just to demo it.. no functional reason :). tf_terms.setDocument(new JTextFieldLimit(4)); // JTextFieldLimit is an inner class defined at teh bottom of this file. tf_interest = new JTextField(); tf_principal = new JTextField(); calc_button = new JButton("Calculate"); // add the action listener calc_button.addActionListener(this); clear_button = new JButton("Clear"); // me // add the clear action command me clear_button.setActionCommand ("Clear");// me exit_button = new JButton("Exit"); // add the action listener exit_button.addActionListener(this); // lay the components out // all of these are on the first row (y=0) leftpanel.add(option1, gridBagConstraints); gridBagConstraints.gridx = 1; leftpanel.add(option2, gridBagConstraints); gridBagConstraints.gridx = 2; leftpanel.add(option3, gridBagConstraints); // **** Second row gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; leftpanel.add(lb_terms, gridBagConstraints); gridBagConstraints.gridx = 1; // we want the text fields to go across 2 cells gridBagConstraints.gridwidth = 2; // ... and we want it to fill the space gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; leftpanel.add(tf_terms, gridBagConstraints); // set everything back to default gridBagConstraints.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints.gridwidth = 1; // **** Third row gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; leftpanel.add(lb_interest, gridBagConstraints); gridBagConstraints.gridx = 1; // we want the text fields to go across 2 cells gridBagConstraints.gridwidth = 2; // ... and we want it to fill the space gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; leftpanel.add(tf_interest, gridBagConstraints); // set everything back to default gridBagConstraints.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints.gridwidth = 1; // **** Fourth row gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; leftpanel.add(lb_principal, gridBagConstraints); gridBagConstraints.gridx = 1; // we want the text fields to go across 2 cells gridBagConstraints.gridwidth = 2; // ... and we want it to fill the space gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; leftpanel.add(tf_principal, gridBagConstraints); // set everything back to default gridBagConstraints.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints.gridwidth = 1; // **** Fith Row gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; // Buttons are sort of funny, so we have to do a little extra work to get them to look right // in this layout. I will create individual contraints for each... you could create constrains // for every component, and in a more sophisticated layout, you probably would. // **** Sixth row GridBagConstraints calc_constraints = new GridBagConstraints(); calc_constraints.insets = new java.awt.Insets(0, 0, 0, 0); calc_constraints.gridy = 5; calc_constraints.ipadx = 13; calc_constraints.ipady = 11; calc_constraints.gridx = 0; leftpanel.add(calc_button, calc_constraints); GridBagConstraints clear_constraints = new GridBagConstraints();// me clear_constraints.insets = new java.awt.Insets(0, 0, 0, 0); //me clear_constraints.gridy = 5; //me clear_constraints.ipadx = 27; //me clear_constraints.ipady = 11; //me clear_constraints.gridx = 1; // me leftpanel.add(clear_button, clear_constraints); // me GridBagConstraints exit_constraints = new GridBagConstraints(); exit_constraints.insets = new java.awt.Insets(0, 0, 0, 0); exit_constraints.gridy = 5; exit_constraints.ipadx = 40; exit_constraints.ipady = 11; exit_constraints.gridx = 2; leftpanel.add(exit_button, exit_constraints);

// put the left hand side in the split pane splitpane.setLeftComponent(leftpanel);

ActionListener EraseFieldsListener = new EraseFieldsListener(); // sets clear listener me clear_button.addActionListener(EraseFieldsListener); // me clear_button.addActionListener(this); // me

RadioListener myListener = new RadioListener(); // my method { option1.addActionListener(myListener); option2.addActionListener(myListener); option3.addActionListener(myListener); }

}

class RadioListener implements ActionListener // my class { public void actionPerformed(ActionEvent evt) {

if (evt.getActionCommand() == "1") { tf_terms.setText("7"); tf_interest.setText("5.35"); } if (evt.getActionCommand() == "2") { tf_terms.setText("15"); tf_interest.setText("5.50"); } if (evt.getActionCommand() == "3") { tf_terms.setText("30"); tf_interest.setText("5.75"); }

}

}

/* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ // me public class EraseFieldsListener implements ActionListener // listener class for the clear button (my addition) { public void actionPerformed(ActionEvent ev) { Object source = ev.getSource(); if (source == clear_button) { tf_terms.setText(""); // clears the loan amount field tf_interest.setText(""); // clears the term field tf_principal.setText(""); // clears the payment field amortization_out.setText(""); // clears amortization output

} }

} // me

public void actionPerformed(ActionEvent e) { Calculator calculator = new Calculator(); // call our MortgageCalc class

Object source = e.getSource(); if (source == exit_button) { System.exit(0); }

if (source == calc_button) {

try { double principle = Double.parseDouble(tf_principal.getText()); // this throws a NumberFormatException if the text is not a number double rate = Double.parseDouble(tf_interest.getText()); int terms = Integer.parseInt(tf_terms.getText()); } catch (NumberFormatException nfe) { // Tell the user about the error... JOptionPane.showMessageDialog(null, "Please make sure all your entries are numeric!", "USER INPUT ERROR", JOptionPane.ERROR_MESSAGE); } }

}

/** * Inner class to limit the size of a text field. * Could be in a seperate file, but since we are only using it for this class, it should be here. * * NOTE: This is not the same as defining 2 classes in the same file. This class is part of the top class * That is why it is consided an inner class. Other than this type of thing, you have no reason to have * an inner class in your work. * * Also, if you want to limit the input of a text field in your code, feel free to copy this as is and use it. */ public class JTextFieldLimit extends PlainDocument { private static final long serialVersionUID = -349808007443039827L; private int limit; // optional uppercase conversion private boolean toUppercase = false;

JTextFieldLimit(int limit) { super(); this.limit = limit; } /** * Sets the limit, and if you pass in true here.. will force the * input to upper case before displaying it. * @param limit * @param upper */ JTextFieldLimit(int limit, boolean upper) { super(); this.limit = limit; toUppercase = upper; } /** * This is a callback method used by Java when text is entered into a text field. This is the * place we can check the length before we actually place the character in the GUI. */ public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) return;

if ((getLength() + str.length()) <= limit) { if (toUppercase) str = str.toUpperCase(); super.insertString(offset, str, attr); } } }

/** * MAIN... the entry point to this program * @param args */ public static void main(String[] args) { LayoutExample1 example = new LayoutExample1(); example.setVisible(true); }

public class Calculator // me..to the end {

Double s; Double MPayAmt; Double Amount = Double.parseDouble(tf_principal.getText()); // retrieves the loan amount Double term = Double.parseDouble(tf_terms.getText()); // retrieves the loan terms Double rate = Double.parseDouble(tf_interest.getText());{ // retrieves the inputed interest rate rate = rate /100/12; // is the monthly interest rate calculation s = 1 + rate; // this is adding one onto r to effectively calculate Math.pow term = term * 12; // this converts terms into months MPayAmt = (rate / (1 - Math.pow(s, -term))) * Amount; // calculates payment, formula retrieved from http://www.financialone.com/mortgages/mortcalcs DecimalFormat numFormatter = new DecimalFormat("#,##0.00"); // formats the decimal output String MPaymentFmt = numFormatter.format(MPayAmt); double principal=Amount; int month; StringBuffer buffer = new StringBuffer(); buffer.append("Month\tAmount\tInterest\tBalance\n"); for (int i=0; i<term; i++) { month=i+1; double interest=(principal*rate); double balance=principal-(MPayAmt-interest); buffer.append(month+"\t"); buffer.append(new String(numFormatter.format(principal)) + "\t"); buffer.append(new String(numFormatter.format(interest)) + "\t"); buffer.append(new String(numFormatter.format(balance)) + "\n"); principal=balance; }

amortization_out.setText(buffer.toString()); } // cannot put closing curly brace ?? } }

[/code][noparse]

// import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.*;


/**
 * This is code based on the layout design created by David Lilley
 * POS 407 student January 2006. He wanted this layout and could not
 * achieve it as he wanted. I wrote the code to show him how to do it in
 * return for me using the code as an example for future classes. I hope you
 * enjoy.
 * @author Chip Dickson
 */
public class LayoutExample1 extends JFrame implements ActionListener
{
	private static final long serialVersionUID = 4364582253350924044L;

	private Container jContentPane = null;
	private JSplitPane splitpane = null;
	private JPanel leftpanel = null;
	private JScrollPane rightpane = null;
	private JTextArea amortization_out = null;
	private JRadioButton option1 = null;
	private JRadioButton option2 = null;
	private JRadioButton option3 = null;
	private ButtonGroup btgroup_options;
	private ButtonGroup btgroup_plans;
	private JLabel lb_terms = null;
	private JTextField tf_terms = null;
	private JLabel lb_interest = null;
	private JTextField tf_interest = null;
	private JLabel lb_principal = null;
	private JTextField tf_principal = null;
	private JButton calc_button = null;
	private JButton clear_button = null;  // me
	private JButton exit_button = null;

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

	private void initialize()
	{
		// set up the basics
		jContentPane = this.getContentPane();
		setTitle("Mcbride Financial Services Mortgage Calculator");   // I changed title
		setSize(600, 200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Notice the top pane is just a simple BoxLayout
		jContentPane.setLayout(new BoxLayout(jContentPane, BoxLayout.Y_AXIS));
		// create a splitpane to layout out code
		splitpane = new JSplitPane();
		splitpane.setDividerSize(2);
		splitpane.setDividerLocation(300); // set the divider right in the middle
		//splitpane.setEnabled(false); // locks the divider bar
		// Call the method to load the left side of the split pane
		loadLeftSide();
		// load the right side of the split pane
		loadRightSide();
		// add the split pane to the content pane
		jContentPane.add(splitpane, null);
	}

	/**
	 *
	 */
	private void loadRightSide()
	{
		// Not much to the right side... just a JScrollPane and the textArea to go in it...
		rightpane = new JScrollPane();
		// make the scroll bars always be there
		rightpane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		rightpane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		// give ourselves a nice boarder
		rightpane.setViewportBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
		amortization_out = new JTextArea();
		Font displayFont = new Font("Serif", Font.BOLD, 14);

		// don't want folks typing in here... so we better not let them.
		amortization_out.setEditable(false);
		amortization_out.setFont(displayFont);
		amortization_out.setText("");

		rightpane.setViewportView(amortization_out);
		splitpane.setRightComponent(rightpane);
	}

	/**
	 *
	 */
	private void loadLeftSide()
	{
		leftpanel = new JPanel();
		leftpanel.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
		// add a nice boarder to the panel
		leftpanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.SoftBevelBorder.LOWERED));
		//		 we are using a grid bag layout for this...
		leftpanel.setLayout(new GridBagLayout());
		// we want 2 button groups (one on top, one on the bottom)
		// this is how you make your radio buttons turn off when another is clicked on
		btgroup_options = new ButtonGroup();
		btgroup_plans = new ButtonGroup();

		// GridBagLayout Base constraints
		GridBagConstraints gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 0);
		gridBagConstraints.gridy = 0;
		gridBagConstraints.ipadx = 0;
		gridBagConstraints.ipady = 0;
		gridBagConstraints.gridx = 0;
		// Create all our components
		option1 = new JRadioButton("Option 1");
		option2 = new JRadioButton("Option 2");
		option3 = new JRadioButton("Option 3");
		// put the buttons in a group
		btgroup_options.add(option1);
		option1.setSelected(false); // sets the default button on
		option1.setActionCommand("1");   // me
		option2.setActionCommand("2");   // me
		option3.setActionCommand("3");   // me
		btgroup_options.add(option2);
		btgroup_options.add(option3);
		lb_terms = new JLabel("Terms");
		lb_interest = new JLabel("Interest");
		lb_principal = new JLabel("Principal");
		tf_terms = new JTextField();
		// limits the number of characters to 4, just to demo it.. no functional reason :).
		tf_terms.setDocument(new JTextFieldLimit(4)); // JTextFieldLimit is an inner class defined at teh bottom of this file.
		tf_interest = new JTextField();
		tf_principal = new JTextField();
		calc_button = new JButton("Calculate");
		// add the action listener
		calc_button.addActionListener(this);
		clear_button = new JButton("Clear");  // me
		// add the clear action command         me
		clear_button.setActionCommand ("Clear");// me
		exit_button = new JButton("Exit");
		// add the action listener
		exit_button.addActionListener(this);
		// lay the components out
		// all of these are on the first row (y=0)
		leftpanel.add(option1, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		leftpanel.add(option2, gridBagConstraints);
		gridBagConstraints.gridx = 2;
		leftpanel.add(option3, gridBagConstraints);
		// **** Second row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		leftpanel.add(lb_terms, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_terms, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		//  **** Third row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 2;
		leftpanel.add(lb_interest, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_interest, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		//  **** Fourth row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 3;
		leftpanel.add(lb_principal, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_principal, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		// **** Fith Row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 4;
		// Buttons are sort of funny, so we have to do a little extra work to get them to look right
		// in this layout. I will create individual contraints for each... you could create constrains
		// for every component, and in a more sophisticated layout, you probably would.
		// **** Sixth row
		GridBagConstraints calc_constraints = new GridBagConstraints();
		calc_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
		calc_constraints.gridy = 5;
		calc_constraints.ipadx = 13;
		calc_constraints.ipady = 11;
		calc_constraints.gridx = 0;
		leftpanel.add(calc_button, calc_constraints);
		GridBagConstraints clear_constraints = new GridBagConstraints();// me
		clear_constraints.insets = new java.awt.Insets(0, 0, 0, 0);     //me
		clear_constraints.gridy = 5;                                     //me
		clear_constraints.ipadx = 27;                                     //me
		clear_constraints.ipady = 11;                                    //me
		clear_constraints.gridx = 1;                                     // me
		leftpanel.add(clear_button, clear_constraints);                 // me
		GridBagConstraints exit_constraints = new GridBagConstraints();
		exit_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
		exit_constraints.gridy = 5;
		exit_constraints.ipadx = 40;
		exit_constraints.ipady = 11;
		exit_constraints.gridx = 2;
		leftpanel.add(exit_button, exit_constraints);

		// put the left hand side in the split pane
		splitpane.setLeftComponent(leftpanel);

		ActionListener EraseFieldsListener = new EraseFieldsListener();  // sets clear listener  me
		clear_button.addActionListener(EraseFieldsListener);             // me
        clear_button.addActionListener(this);                            // me

        RadioListener myListener = new RadioListener();     // my method
        {
			option1.addActionListener(myListener);
			option2.addActionListener(myListener);
			option3.addActionListener(myListener);
		}

	}



	class RadioListener implements ActionListener  // my class
	{
			public void actionPerformed(ActionEvent evt)
			{

				if (evt.getActionCommand() == "1")
				{
					tf_terms.setText("7");
					tf_interest.setText("5.35");
				}
				if (evt.getActionCommand() == "2")
				{
					tf_terms.setText("15");
					tf_interest.setText("5.50");
				}
				if (evt.getActionCommand() == "3")
				{
					tf_terms.setText("30");
					tf_interest.setText("5.75");
				}

			}

	}




	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
     // me
	 public class EraseFieldsListener implements ActionListener          // listener class for the clear button   (my addition)
	 {
		 public void actionPerformed(ActionEvent ev)
		 {
			 Object source = ev.getSource();
			 if (source == clear_button)
			 {
				 tf_terms.setText("");                          // clears the loan amount field
			 	 tf_interest.setText("");                       // clears the term field
			 	 tf_principal.setText("");                      // clears the payment field
			 	 amortization_out.setText("");                  // clears amortization output

			 }
		 }


    }   // me


	public void actionPerformed(ActionEvent e)
	{
		Calculator calculator = new Calculator();  // call our MortgageCalc class

		Object source = e.getSource();
		if (source == exit_button)
		{
			System.exit(0);
		}



		if (source == calc_button)
		{


			try
			{
				double principle = Double.parseDouble(tf_principal.getText()); // this throws a NumberFormatException if the text is not a number
				double rate = Double.parseDouble(tf_interest.getText());
				int terms = Integer.parseInt(tf_terms.getText());
			}
			catch (NumberFormatException nfe)
			{
				// Tell the user about the error...
				JOptionPane.showMessageDialog(null, "Please make sure all your entries are numeric!", "USER INPUT ERROR", JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	/**
	 * Inner class to limit the size of a text field.
	 * Could be in a seperate file, but since we are only using it for this class, it should be here.
	 *
	 * NOTE: This is not the same as defining 2 classes in the same file. This class is part of the top class
	 * That is why it is consided an inner class. Other than this type of thing, you have no reason to have
	 * an inner class in your work.
	 *
	 * Also, if you want to limit the input of a text field in your code, feel free to copy this as is and use it.
	 */
	public class JTextFieldLimit extends PlainDocument
	{
		private static final long serialVersionUID = -349808007443039827L;
		private int limit;
		// optional uppercase conversion
		private boolean toUppercase = false;

		JTextFieldLimit(int limit)
		{
			super();
			this.limit = limit;
		}
		/**
		 * Sets the limit, and if you pass in true here.. will force the
		 * input to upper case before displaying it.
		 * @param limit
		 * @param upper
		 */
		JTextFieldLimit(int limit, boolean upper)
		{
			super();
			this.limit = limit;
			toUppercase = upper;
		}
		/**
		 * This is a callback method used by Java when text is entered into a text field. This is the
		 * place we can check the length before we actually place the character in the GUI.
		 */
		public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException
		{
			if (str == null)
				return;

			if ((getLength() + str.length()) <= limit)
			{
				if (toUppercase)
					str = str.toUpperCase();
				super.insertString(offset, str, attr);
			}
		}
	}



	/**
	 * MAIN... the entry point to this program
	 * @param args
	 */
	public static void main(String[] args)
	{
		LayoutExample1 example = new LayoutExample1();
		example.setVisible(true);
	}

	public class Calculator  // me..to the end
	{

		Double s;
		Double MPayAmt;
		Double Amount = Double.parseDouble(tf_principal.getText()); // retrieves the loan amount
		Double term = Double.parseDouble(tf_terms.getText());     // retrieves the loan terms
		Double rate = Double.parseDouble(tf_interest.getText());{      // retrieves the inputed interest rate
		rate = rate /100/12;  // is the monthly interest rate calculation
		s = 1 + rate;         // this is adding one onto r to effectively calculate Math.pow
		term = term * 12;     // this converts terms into months
		MPayAmt = (rate / (1 - Math.pow(s, -term))) * Amount;	// calculates payment, formula retrieved from http://www.financialone.com/mortgages/mortcalcs
		DecimalFormat numFormatter = new DecimalFormat("#,##0.00"); // formats the decimal output
		String MPaymentFmt = numFormatter.format(MPayAmt);
		double principal=Amount;
		int month;
		StringBuffer buffer = new StringBuffer();
		buffer.append("Month\tAmount\tInterest\tBalance\n");
		for (int i=0; i<term; i++)
		{
			month=i+1;
			double interest=(principal*rate);
			double balance=principal-(MPayAmt-interest);
			buffer.append(month+"\t");
			buffer.append(new String(numFormatter.format(principal)) + "\t");
			buffer.append(new String(numFormatter.format(interest)) + "\t");
			buffer.append(new String(numFormatter.format(balance)) + "\n");
			principal=balance;
		}

		amortization_out.setText(buffer.toString());
		}
	//  cannot put closing curly brace ??
	}
}

Again, code tags! You apparently hit "Reply" and got my [noparse] tag in there. You need to type in the code tags yourself.

Frankly i was a little surprised the program worked as it did. I thought you had to specify a constructor when you called it:

public class Calculator // me..to the end
    {

        Double s;
        Double MPayAmt;
        Double Amount = Double.parseDouble(tf_principal.getText()); // retrieves the loan amount
        Double term = Double.parseDouble(tf_terms.getText()); // retrieves the loan terms
        Double rate = Double.parseDouble(tf_interest.getText());


        { // retrieves the inputed interest rate
            rate = rate / 100 / 12; // is the monthly interest rate calculation
            s = 1 + rate; // this is adding one onto r to effectively calculate Math.pow
            term = term * 12; // this converts terms into months
            MPayAmt = (rate / (1 - Math.pow(s, -term))) * Amount; // calculates payment, formula retrieved from http://www.financialone.com/mortgages/mortcalcs
            DecimalFormat numFormatter = new DecimalFormat("#,##0.00"); // formats the decimal output
            String MPaymentFmt = numFormatter.format(MPayAmt);
            double principal = Amount;
            int month;
            StringBuffer buffer = new StringBuffer();
            buffer.append("Month\tAmount\tInterest\tBalance\n");
            for (int i = 0; i < term; i++)
            {
                month = i + 1;
                double interest = (principal * rate);
                double balance = principal - (MPayAmt - interest);
                buffer.append(month + "\t");
                buffer.append(new String(numFormatter.format(principal)) + "\t");
                buffer.append(new String(numFormatter.format(interest)) + "\t");
                buffer.append(new String(numFormatter.format(balance)) + "\n");
                principal = balance;
            }

            amortization_out.setText(buffer.toString());
        }
// cannot put closing curly brace ??
    }

You don't have anything that says Calculator () , so I guess it's assumed that the whole thing is the constructor or something? That's what my debugging/breakpoints suggest. Anyway, I would explicitly put a constructor in if you intend to call it as you do in your actionPerformed:

public void actionPerformed(ActionEvent e)
    {
        Calculator calculator = new Calculator(); // call our MortgageCalc class

        Object source = e.getSource();
        if (source == exit_button)
        {
            System.exit(0);
        }

You won't get past line 3 above if you just hit the Exit button like I did because in your Calculator class, you parse empty Strings into doubles, which you can't do.

Not sure why you are calling a Calculator () constructor at the top of actionPerformed, especially when you are just exiting. But that's what the problem is. You can't parse an empty TextBox into a number.

This article has been dead for over six months. Start a new discussion instead.