I am working on an Graphical User Interface, which uses two JTextFields(the third one shouldnt be relevant to this question) and a JComboBox. The selected Item from the ComboBox should decide which Textfield is added to the Arraylist "Gewínner" if the Button "Speichern" is pressed.
I am not allowed to use an inner class for the Listener.
Now the Problem: Whenever my ActionPerformed-method gets used i get an NullpointerException in the getGewinner-method. With the help of System.out.print I found that the null that gets pointed is the variable Winner in the call Winner.getSelectedItem().toString().
The Question: Why is Winner == null? Shouldnt it be initiated in the constructor? How can I change it ?
The Code In Question:
The GUI:
public class ErgebnisFrame extends JFrame{
private JLabel Spieler1, Spieler2, Gewinner, Punkte;
private JTextField one, two;
private JComboBox <String> Winner;
private JButton Abbruch, Speichern;
public ErgebnisFrame(){
super();
this.setVisible(true);
this.setLayout(new GridLayout(5,2));
this.setSize(300,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Spieler1 = new JPanel();
Spieler1.add(new JLabel("Name von Spieler 1"));
this.add(Spieler1);
JTextField one = new JTextField(1);
this.add(one);
JPanel Spieler2 = new JPanel();
Spieler2.add(new JLabel("Name von Spieler 2"));
this.add(Spieler2);
JTextField two = new JTextField(1);
this.add(two);
JPanel Gewinner = new JPanel();
Gewinner.add(new JLabel("Gewinner"));
this.add(Gewinner);
JComboBox<String> Winner = new JComboBox <String>();
Winner.addItem("Spieler 1");
Winner.addItem("Spieler 2");
this.add(Winner);
JPanel Punkte = new JPanel();
Punkte.add(new JLabel("Punkte des Gewinners"));
this.add(Punkte);
JTextField points = new JTextField(1);
this.add(points);
JButton Abbruch = new JButton("Abbrechen");
JButton Speichern = new JButton("Speichern");
Speichern.setActionCommand("Speichern");
Speichern.addActionListener(new SpeichernListener(this));
this.add(Abbruch);
this.add(Speichern);
}
public String getSpielerName(int Par){
switch(Par){
case 1: return one.getText();
case 2: return two.getText();
default: return "Es gibt nur zwei Spieler";
}
}
public String getSpieler1Name(){
return one.getText();
}
public String getSpieler2Name(){
return two.getText();
}
public String getGewinner(){
return Winner.getSelectedItem().toString();
}
public static void main (String [] args){
ErgebnisFrame Haupt = new ErgebnisFrame();
}
}
the Listener:
public class SpeichernListener implements ActionListener {
private ErgebnisFrame Frame;
private static List <String> gewinner = new ArrayList <String>();
public SpeichernListener(ErgebnisFrame frame){
this.Frame = frame;
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Speichern")){
if(Frame.getGewinner().equals("Spieler 1")){
gewinner.add(Frame.getSpieler1Name());
}
else{
gewinner.add(Frame.getSpieler2Name());
}
}
}
public List <String> getGewinner(){
return gewinner;
}
}