I am trying to write a program for a simple calculator that just adds two numbers and shows it in a JLabel
. I have managed to design a working Window, Button, etc. But if I click the Button the Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
- Error happens and I don´t know how to solve it.
Here is the code :
import java.awt.EventQueue;
public class Rechnerwin {
private JFrame frame;
private JTextField textFielda;
private JTextField textFieldb;
private JLabel label;
int A;
int B;
int C;
String a;
String b;
String c;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Rechnerwin window = new Rechnerwin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Rechnerwin() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textFielda = new JTextField();
textFielda.setBounds(44, 41, 86, 20);
frame.getContentPane().add(textFielda);
textFielda.setColumns(10);
textFieldb = new JTextField();
textFieldb.setBounds(307, 41, 86, 20);
frame.getContentPane().add(textFieldb);
textFieldb.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String a = textFielda.getText();
String b = textFieldb.getText();
int A = Integer.parseInt(a);
int B = Integer.parseInt(b);
int C = A + B;
String c = Integer.toString(C);
label.setText(c);
}
});
btnAdd.setBounds(169, 85, 89, 23);
frame.getContentPane().add(btnAdd);
JLabel label = new JLabel("a");
label.setBounds(146, 184, 131, 20);
frame.getContentPane().add(label);
}
}