I'm writing a program to calculate the final yield of a person investing a initial amount of money over a set amount of time with a set interest rate. I get the following error when compiling the code:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at calculator.<init>(calculator.java:62)
at calculator.main(calculator.java:92)
Here is the code for my java program:
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class calculator extends JFrame{ private JButton calcButton, clearButton; private JLabel originalDeposit, interestRate, timeInvested; private JLabel resultDisplay; private JTextField originalField, interestField, timeField; private JPanel panel1, panel2, panel3,panel4,panel5; double deposit,interest,time,newBalance; public calculator(){ super("App to calculate the yield of an invesment"); setSize(400,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(6,1)); originalDeposit = new JLabel("Enter amount of original deposit"); originalField = new JTextField(7); interestRate = new JLabel("Enter the annual interest rate"); interestField = new JTextField(5); timeInvested = new JLabel("Enter the years of invesment as a whole number"); calcButton = new JButton("Calculate"); clearButton = new JButton("Clear"); resultDisplay = new JLabel("The new balance in the investment account will be" + newBalance); calcButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String caption = e.getActionCommand(); if(e.getSource() instanceof JButton){ Object String; if("Calculate".equals(caption)) getNewBalance(); resultDisplay.setText("The new balance in the investment account will be" + newBalance); } } }); clearButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String caption = e.getActionCommand(); if(e.getSource() instanceof JButton){ if("Clear".equals(caption)) clearFields(); } } }); panel1 = new JPanel(); panel1.add(originalDeposit); panel1.add(originalField); panel2 = new JPanel(); panel2.add(interestRate); panel2.add(interestField); panel3 = new JPanel(); panel3.add(timeInvested); panel3.add(timeField); panel4 = new JPanel(); panel4.add(calcButton); panel4.add(clearButton); panel5 = new JPanel(); panel5.add(resultDisplay); add(panel1); add(panel2); add(panel3); add(panel4); add(panel5); } public double getNewBalance(){ deposit = Double.parseDouble(originalField.getText().trim()); interest = Double.parseDouble(interestField.getText().trim()); time = Double.parseDouble(timeField.getText().trim()); newBalance = deposit*(1+(interest/1)); return newBalance; } public void clearFields(){ originalField.setText(" "); interestField.setText(" "); timeField.setText(" "); } public static void main(String args[]){ calculator cal = new calculator(); } }