For an assignment I have to make a Java application and one of the functions I'm having a problem with is adding to an ArrayList
. The ArrayList
is in a different class then the method and I get a nullpointer (doesn't happen when I make it static).
This is the code where I'm trying to add:
if (e.getSource() == voegToe) {
if (naam.equals("") || straat.equals("") || huisnummer.equals("")
|| postcode.equals("") || plaats.equals("")
|| telefoonnummer.equals("") || email.equals("")) {
allesoke = false;
foutmelding += "\n";
}
if (allesoke == true) {
Klant newKlant = new Klant (naam, postcode, huisnummer);
System.out.println("HOI");
klantenBindingRef.alleKlanten.add(newKlant);
System.out.println(klantenBindingRef.alleKlanten);
} else {
JOptionPane.showMessageDialog(null, foutmelding, "Foutmelding",
JOptionPane.INFORMATION_MESSAGE, null);
}
And this is part of the code of the class with the ArrayList
:
public class Klantenbinding {
private String naam;
protected List<Klant> alleKlanten = new ArrayList<Klant> ();
// klanten
public void voegKlantToe(Klant nweKlant) {
if (!heeftKlant(nweKlant.getNaam())) {
alleKlanten.add(nweKlant);
}
}
public boolean heeftKlant(String naam) {
boolean b = false;
for (Klant k : alleKlanten) {
if (k.getNaam() == naam) {
b = true;
}
}
return b;
}
The nullpointer comes from the line:
klantenBindingRef.alleKlanten.add(newKlant);
public class KlantToevoegen extends JFrame implements ActionListener {
/**
*
*/
JFrame frame;
private static final long serialVersionUID = 1L;
private JButton voegToe, terug;
private JPanel contentPane;
private JTextField nmTf, strTf, hnrTf, pcTf, plTf, telnrTf, emailTf;
private JLabel lblAanhef, lblNaam, lblStraat, lblNieuweKlantToevoegen,
lblHuisnr, lblPostcode, lblPlaats, lblTelnr, lblEmail;
private JComboBox aanhefBox;
private Klantenbinding klantenBindingRef;
private AutoToevoegenFrame autoToevoegenFrameRef;
private JSeparator separator;
private JSeparator separator_1;
/**
* Launch the application.
*/
Did you try importing the class with the ArrayList in it? (can't comment yet)
我敢打赌,您的变量klantenBindingRef
永远不会初始化。
Try comparing your strings in this way to avoid NPE
if ("".equals(naam) || "".equals(straat) || ...) {
allesoke = false;
foutmelding += "\n";
}
then verify that klantenBindingRef is instantiated before access to his variables
//klantenBindingRef is null
klantenBindingRef = new Klantenbinding();
klantenBindingRef.alleKlanten
...
initialize your varibale klantenBindingRef
before use klantenBindingRef = new Klantenbinding();
if( klantenBindingRef == null )
klantenBindingRef = new Klantenbinding();
klantenBindingRef.alleKlanten.add(newKlant);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.