Reputation: 2652
Hello I have created a application with several buttons in it. but when I press a button I get the NullPointerException. The strange thing here is that nothing is empty ( null )
here a code example
public class MuseumPanel extends JPanel implements ActionListener {
private JTextField kaartnummer;
private JTextField uur, minuut;
private JButton aankomst, vertrek, overzicht, sluiting;
private int hour;
private int minute;
private final int REFRESH = 1000;
MuseumRegistratie museum;
public MuseumPanel(MuseumRegistratie museum) {
// zorg ervoor dat de huidige tijd wordt opgehaald.
javax.swing.Timer timer = new javax.swing.Timer(REFRESH, this);
timer.start();
kaartnummer = new JTextField(15);
uur = new JTextField(2);
minuut = new JTextField(2);
aankomst = new JButton("Komt binnen");
aankomst.addActionListener(this);
vertrek = new JButton("Vertrekt");
vertrek.addActionListener(this);
overzicht = new JButton("aantal aanwezig");
overzicht.addActionListener(this);
sluiting = new JButton("sluiting");
sluiting.addActionListener(this);
add(new JLabel("Kaartnummer"));
add(kaartnummer);
add(new JLabel("tijdstip van aankomst of vertrek "));
add(uur);
add(new JLabel(" uur en "));
add(minuut);
add(new JLabel(" minuten"));
add(aankomst);
add(vertrek);
add(overzicht);
add(sluiting);
}
@Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
hour = now.get(Calendar.HOUR_OF_DAY);
minute = now.get(Calendar.MINUTE);
uur.setText("" + hour);
minuut.setText("" + minute);
// aankomst
if(e.getSource() == aankomst) {
try {
museum.checkIn(kaartnummer.getText(), hour, minute);
} catch (NullPointerException ex) {
System.out.println("cardnumber: " + kaartnummer.getText() + " hour " + hour + " minute " + minute);
}
}
// vertrek
if(e.getSource() == vertrek) {
museum.checkOut(kaartnummer.getText(), hour, minute);
}
// overzicht
if(e.getSource() == overzicht) {
museum.getAantalAanwezig();
}
// sluiting
if(e.getSource() == sluiting) {
museum.sluitRegistratie();
}
}
}
When pressing this button for example I get the exception with every variable correctly.. Does anyone know how this appears and how to solve it?
Upvotes: 0
Views: 141
Reputation: 8200
Without further information I would assume that the museum object is null which would trigger the nullpointerexception when you try to call museum.checkIn.
Looking at the Code museum is definitely null. in the constructor you should include:
this.museum = museum;
Assuming the museum object you pass in is NOT null then everything else should work.
Upvotes: 3
Reputation: 106389
You don't seem to be assigning a value to museum
in your constructor, yet you dereference it in a lot of places. You'd want to do this:
this.museum = museum;
somewhere in your constructor. Alternatively, rename the variable so you don't accidentally do museum = museum
, which would have no effect.
Upvotes: 2