I am struggling why the button does not appear on GUI when I run it. I am creating the Calculator by using Java. I am testing the two buttons ( del button and clr button) before going further since I want to double check if my current code run well.
However, when I tried it, my buttons didn't appear. I do not know where I did wrong. Could you take a look at my code and assist me what is the problem?
package phan;
/**
*
* @author bemua
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator implements ActionListener {
/**
* @param args the command line arguments
*/
JFrame frame;
JTextField textField;
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[9];
JButton addButton, subButton, mulButton, divButton;
JButton decButton, equButton, delButton, clrButton;
JPanel panel;
Font myFont = new Font("Ink Free", Font.BOLD, 30);
double num1 = 0, num2 = 0, result = 0;
char operator;
Calculator(){
// create frame
frame = new JFrame("CALCULATOR");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 550);
frame.setLayout(null);
frame.pack();
// create text field
textField = new JTextField();
textField.setBounds(50,25,300,50); //setBounds.(x,y,width, height
textField.setFont(myFont);
textField.setEditable(true);
// create button
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
decButton = new JButton(".");
equButton = new JButton("=");
delButton = new JButton("Delete");
clrButton = new JButton("Clear");
// array contains function
functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
functionButtons[4] = decButton;
functionButtons[5] = equButton;
functionButtons[6] = delButton;
functionButtons[7] = clrButton;
for ( int i = 0; i < 9;i++) {
functionButtons[i].addActionListener(this);
functionButtons[i].setFont(myFont);
functionButtons[i].setFocusable(false);
}
for ( int i = 0; i < 10 ;i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
numberButtons[i].setFont(myFont);
numberButtons[i].setFocusable(false);
}
delButton.setBounds(50,430,145,50);
clrButton.setBounds(50,430,145,50);
frame.add(delButton, BorderLayout.SOUTH);
frame.add(clrButton, BorderLayout.SOUTH);
frame.add(textField);
frame.setVisible(true);
}
public static void main(String[] args) {
Calculator calc = new Calculator();
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
Here is the error after I run the code:
run:
Exception in thread "main" java.lang.NullPointerException
at phan.Calculator.<init>(Calculator.java:69)
at phan.Calculator.main(Calculator.java:95)