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 13 of 13

Thread: Code from textbook not working and I don't know why--Event-driven programming

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    10
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Code from textbook not working and I don't know why--Event-driven programming

    Hello,

    I am trying to learn event-driven programming, so I coded up an entire program from a textbook that is meant to simulate a monthly payment calculator for a loan. The loan amount, interest rate, and duration of the loan are given as inputs to JTextFields, and the payment amount is supposed to be output into a fourth JTextField.

    But even though I copied the program line-for-line from the book, it will not work. The GUI looks fine, but when I try to calculate the payment, it gives me a LONG list of errors (which I confess I don't really know how to interpret--I would like to learn). I would really appreciate it if someone could tell me what is wrong with this code so that I have a correct program to learn from. Here is the code, followed by the errors:

    public class LoanPayment    //a utility class that calculates monthly payment based on three //variables. The math is all based on a standard formula, also copied exactly from book.
    {
        public static double getPayment(double amount, double interest, double years)
        {
            double payment = amount * ((interest/1200.0)/(1 - Math.pow(1 + interest/1200.0, -years * 12)));
            return (Math.round(payment * 100))/100.00;      //rounds to 2 decimal places
        }
    }

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class LoanCalculator extends JFrame
    {
        private JTextField amountField;
        private JTextField interestField;
        private JTextField yearsField;
        private JTextField paymentField;
        private JButton submitButton;
        private JButton clearButton;
        private JButton exitButton;
     
        public LoanCalculator()
        {
            super("Monthly Payment");
            setBounds(0, 0, 250, 200);
            JPanel panel = new JPanel();        //for text fields and labels
     
            //make a label for each text field; add the labels and text fields to the panel
            JLabel amountLabel = new JLabel();
            amountLabel.setFont(new Font("Courier", Font.BOLD, 12));
            amountLabel.setText("  Amount:");
            amountField = new JTextField(10);
            panel.add(amountLabel);
            panel.add(amountField);
     
            JLabel interestLabel = new JLabel();
            interestLabel.setFont(new Font("Courier", Font.BOLD, 12));
            interestLabel.setText("Interest:");
            interestField = new JTextField(10);
            panel.add(interestLabel);
            panel.add(interestField);
     
            JLabel yearsLabel = new JLabel();
            yearsLabel.setFont(new Font("Courier", Font.BOLD, 12));
            yearsLabel.setText("   Years:");
            yearsField = new JTextField(10);
            panel.add(yearsLabel);
            panel.add(yearsField);
     
            JLabel paymentLabel = new JLabel();
            paymentLabel.setFont(new Font("Courier", Font.BOLD, 12));
            paymentLabel.setText(" Payment:");
            JTextField paymentField = new JTextField(10);
            panel.add(paymentLabel);
            panel.add(paymentField);
            paymentField.setEditable(false);
     
            add(panel, BorderLayout.CENTER);
     
            //creat three buttons, add them to a new panel, add panel to bottom of frame
            JPanel buttonPanel = new JPanel();
            submitButton = new JButton("Submit");
            clearButton = new JButton("Clear");
            exitButton = new JButton("Exit");
            buttonPanel.add(submitButton);
            buttonPanel.add(clearButton);
            buttonPanel.add(exitButton);
            add(buttonPanel, BorderLayout.SOUTH);
     
            //register a listener with each button
            submitButton.addActionListener(new ButtonListener());
            clearButton.addActionListener(new ButtonListener());
            exitButton.addActionListener(new ButtonListener());
     
            setResizable(false);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
     
        private class ButtonListener implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                if (e.getSource() == submitButton)
                    try
                    {
                        double amount = Double.parseDouble(amountField.getText());  //possible NumberFormatException
                        double interest = Double.parseDouble(interestField.getText());
                        double years = Double.parseDouble(yearsField.getText());
                        double payment = LoanPayment.getPayment(amount, interest, years);
                        //setText() requires a String reference; 'payment + ""' returns a String
                        paymentField.setText(payment + "");
                    }
                    catch (NumberFormatException excep)
                    {
                        paymentField.setText("Illegal input");
                    }
                else if (e.getSource() == clearButton)
                {
                    amountField.setText("");
                    interestField.setText("");
                    yearsField.setText("");
                    paymentField.setText("");
                }
                else
                    System.exit(0);
            }        
        }
        public static void main(String[] args)
        {
            LoanCalculator frame = new LoanCalculator();
        }
    }


    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at LoanCalculator$ButtonListener.actionPerformed(LoanCalculator.java:85)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    	at java.awt.Component.processMouseEvent(Component.java:6288)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    	at java.awt.Component.processEvent(Component.java:6053)
    	at java.awt.Container.processEvent(Container.java:2041)
    	at java.awt.Component.dispatchEventImpl(Component.java:4651)
    	at java.awt.Container.dispatchEventImpl(Container.java:2099)
    	at java.awt.Component.dispatchEvent(Component.java:4481)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    	at java.awt.Container.dispatchEventImpl(Container.java:2085)
    	at java.awt.Window.dispatchEventImpl(Window.java:2478)
    	at java.awt.Component.dispatchEvent(Component.java:4481)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
    	at java.awt.EventQueue.access$000(EventQueue.java:84)
    	at java.awt.EventQueue$1.run(EventQueue.java:602)
    	at java.awt.EventQueue$1.run(EventQueue.java:600)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    	at java.awt.EventQueue$2.run(EventQueue.java:616)
    	at java.awt.EventQueue$2.run(EventQueue.java:614)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    Thanks!


  2. #2
    Junior Member
    Join Date
    May 2012
    Posts
    11
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    [removed - sorry, accidental double-post]
    Last edited by squeakbox; May 9th, 2012 at 03:00 PM.

  3. #3
    Junior Member
    Join Date
    May 2012
    Posts
    11
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Try this:
    Instead of putting variables such as "double payment" inside your methods, put them with your instance variables, like:

    "private double payment;"

    set them to 0 in your constructor:

    "payment = 0;"

    Then see if it fixes the problem.

    Also, it appears that you didn't instantiate your LoanPayment in your LoanCalculator class. You shouldn't be calling the method as static, you should instantiate the class. (This is probably why you're getting the NullPointerException)

    LoanPayment also has no constructor...

    Also, putting them out of your methods will eat less memory, so do this for all variables.
    Let me know if this helps.
    Last edited by squeakbox; May 9th, 2012 at 03:23 PM.

  4. #4
    Junior Member
    Join Date
    Feb 2012
    Posts
    10
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Thanks for the reply. No, this did not fix the problem. Keep in mind that this is from a textbook, so I'm not looking for a redesign here. Assuming that the authors are not complete idiots, this has to be something simple that I'm just not seeing.

    The method in LoanPayment is static because it is a utility class. Not to be argumentative, but I've seen it done this way before and it works fine. Again, I don't want to fix the aesthetics of the program that two computer scientists wrote--just the error.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,623
    Thanks
    45
    Thanked 1,958 Times in 1,932 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at LoanCalculator$ButtonListener.actionPerformed(Loan Calculator.java:85)
    What variable on line 85 has a null value? When you find the variable, backtrack in the code to see why that variable does not have a valid non-null value.
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    BloomingNutria (May 9th, 2012)

  7. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 299 Times in 282 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Hmm, interesting. None of your GUI objects should be throwing a Null Pointer there because the Container.add(Component) method throws a Null Pointer if the argument is null (meaning if you can add it to the JPanel, it isn't null). Furthermore, I don't think the Double.parseDouble(String) method throws a Null Pointer in any situation.

    This one has me stumped. You'll have the give us more information (such as what line 85 is, like Norm mentioned).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #7
    Junior Member
    Join Date
    May 2012
    Posts
    11
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Quote Originally Posted by BloomingNutria View Post
    Thanks for the reply. No, this did not fix the problem. Keep in mind that this is from a textbook, so I'm not looking for a redesign here. Assuming that the authors are not complete idiots, this has to be something simple that I'm just not seeing.

    The method in LoanPayment is static because it is a utility class. Not to be argumentative, but I've seen it done this way before and it works fine. Again, I don't want to fix the aesthetics of the program that two computer scientists wrote--just the error.
    Alright.

    Well I copyed & pasted your code, and I found the problem. You didn't create "paymentField = new JTextField();", in my IDE, your paymentField comes up as inactive.

  9. The Following User Says Thank You to squeakbox For This Useful Post:

    BloomingNutria (May 9th, 2012)

  10. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,548
    Thanks
    24
    Thanked 299 Times in 282 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Oh, nevermind I found it. paymentField is null. Look at where you initialized it. You created a new local variable instead of initalizing the global variable.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  11. The Following User Says Thank You to aussiemcgr For This Useful Post:

    BloomingNutria (May 9th, 2012)

  12. #9
    Junior Member
    Join Date
    May 2012
    Posts
    11
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    You seem to have written "JTextField paymentField = new JTextField(10);" when you already have "private JTextField paymentField;" at the top as well.

  13. #10
    Junior Member
    Join Date
    Feb 2012
    Posts
    10
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Aha! Thanks, everyone. I just couldn't spot it. I guess the author just put that in twice (I double checked, and it is that way in the book), and I didn't notice. I think my main problem is that I just need to figure out how to read those error messages.

  14. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,623
    Thanks
    45
    Thanked 1,958 Times in 1,932 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    I just need to figure out how to read those error messages.
    Too bad your helpers didn't help you find the problem instead finding the problem for you.

  15. #12
    Junior Member
    Join Date
    May 2012
    Posts
    11
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Quote Originally Posted by Norm View Post
    Too bad your helpers didn't help you find the problem instead finding the problem for you.
    I learned to read errors with someone pointing them out to me, and I find I can read errors myself fine now.
    I'm sure they'll figure it out down the line.

  16. The Following User Says Thank You to squeakbox For This Useful Post:

    BloomingNutria (May 9th, 2012)

  17. #13
    Junior Member
    Join Date
    Feb 2012
    Posts
    10
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Code from textbook not working and I don't know why--Event-driven programming

    Quote Originally Posted by squeakbox View Post
    I learned to read errors with someone pointing them out to me, and I find I can read errors myself fine now.
    I'm sure they'll figure it out down the line.
    Exactly. And indeed, the best way to teach someone something is often to give them information.


    It's not as though I'm asking anyone to write code or do my homework for me. I'm actually a very serious student and I am very good at absorbing information and extrapolating from it. I'm not lazy--I've only been programming for a few months, and I have learned a great deal. I've been told I have a gift for it. I'm not some slacker who is asking other people to do their work for them.

    I'm not pointing any fingers, but there is a lot of information hoarding around forums these days, and it can border on making those forums darned unuseful.

    And that's all I have to say about that. Thanks again to everyone (including Norm) for their help.
    Last edited by BloomingNutria; May 9th, 2012 at 09:01 PM.

Similar Threads

  1. How to Translate working code into code with a Tester Class
    By bankoscarpa in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 15th, 2012, 02:13 PM
  2. Why isn't this code working?
    By tai8 in forum What's Wrong With My Code?
    Replies: 24
    Last Post: March 19th, 2012, 07:00 PM
  3. Code working only on ide
    By xeyos in forum Java Networking
    Replies: 0
    Last Post: November 17th, 2011, 04:40 PM
  4. Is it possible to use same event code for several objects?
    By stab in forum Object Oriented Programming
    Replies: 4
    Last Post: September 27th, 2011, 12:12 PM
  5. Getting code working with gui
    By Nostromo in forum AWT / Java Swing
    Replies: 2
    Last Post: March 21st, 2011, 09:34 PM

Tags for this Thread