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

• May 9th, 2012, 01:44 PM
BloomingNutria
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:

Code :

```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 } }```

Code :

```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(); } }```

Code :

```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!
• May 9th, 2012, 02:51 PM
squeakbox
Re: Code from textbook not working and I don't know why--Event-driven programming
[removed - sorry, accidental double-post]
• May 9th, 2012, 02:55 PM
squeakbox
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.
• May 9th, 2012, 03:49 PM
BloomingNutria
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.
• May 9th, 2012, 03:52 PM
Norm
Re: Code from textbook not working and I don't know why--Event-driven programming
Quote:

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.
• May 9th, 2012, 04:52 PM
aussiemcgr
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).
• May 9th, 2012, 04:53 PM
squeakbox
Re: Code from textbook not working and I don't know why--Event-driven programming
Quote:

Originally Posted by BloomingNutria
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.
• May 9th, 2012, 04:54 PM
aussiemcgr
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.
• May 9th, 2012, 04:58 PM
squeakbox
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.
• May 9th, 2012, 05:38 PM
BloomingNutria
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.
• May 9th, 2012, 05:59 PM
Norm
Re: Code from textbook not working and I don't know why--Event-driven programming
Quote:

I just need to figure out how to read those error messages.
• May 9th, 2012, 06:40 PM
squeakbox
Re: Code from textbook not working and I don't know why--Event-driven programming
Quote:

Originally Posted by Norm

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.
• May 9th, 2012, 08:58 PM
BloomingNutria
Re: Code from textbook not working and I don't know why--Event-driven programming
Quote:

Originally Posted by squeakbox
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.