I am learning Java and I have been working on a problem for about 20 hours but I continue to get a NullPointerException. I do not believe it makes sense after reviewing Sun’s Java Tutorial and my text books. I am trying to add two numbers from text fields as a simple calculator. I have programmed (multiply, divide and subtract) to visually read that the actions are occurring; however, adding two numbers is causing the exception. My code is attached.
Thanks for any assistance.
import java.awt.;
import java.awt.event.;
import java.text.NumberFormat;
import javax.swing.*;
public class FinalCalculator {
public static void main(String[]args){
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class CalculatorFrame extends JFrame{
public CalculatorFrame(){
setTitle(“Brooks Calculator”);
Container contentPane = getContentPane();
CalculatorPanel panel = new CalculatorPanel();
contentPane.add(panel);
pack();
}
}
class CalculatorPanel extends JPanel{
private JLabel display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
private JFormattedTextField inputField1;
private JFormattedTextField inputField2;
public CalculatorPanel(){
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
display = new JLabel("0");
add(display, BorderLayout.NORTH);
// ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("Division", command);
addButton("Add", command);
addButton("Multiply", command);
addButton("Subtract", command);
add(panel, BorderLayout.CENTER);
JFormattedTextField inputField1 = new JFormattedTextField(
NumberFormat.getIntegerInstance());
JFormattedTextField inputField2 = new JFormattedTextField();
inputField1.setText("2");
inputField2.setText("3");
add(inputField1, BorderLayout.EAST);
add(inputField2, BorderLayout.WEST);
}
private void addButton (String label, ActionListener listener){
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class CommandAction implements ActionListener{
public void actionPerformed(ActionEvent evt){
String command = evt.getActionCommand();
// double x = Double.parseDouble(inputField1.getText());
if (start)
{
if (command.equals(“Add”))
{
display.setText(Double.toString(
Double.parseDouble(inputField1.getText())+
Double.parseDouble(inputField2.getText())));
start = false;
}
if (command.equals(“Division”)){
display.setText(command);
}
if (command.equals("Subtract")){
display.setText(command);
}else{
display.setText("Multiply");
}
}
}
}
}