Home > Back-end >  Arraylist turns empty when having contact with listener
Arraylist turns empty when having contact with listener

Time:01-05

Hello I am writing a program for school and I am stuck on this problem where I try to get an arraylist from another class using a button, but when the arraylist comes in contact with the listener it becomes empty. If i try to use the arraylist in another function instead of the listener itself it is still empty.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class addPanel {
    private JPanel panel1;
    private JTextField textField1;
    private JButton OKButton;
    private JButton registreerButton;
    private JTextField textField2;
    private String voorNaam;
    private String achterNaam;

    public addPanel() {

        textField1.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                super.keyReleased(e);
                voorNaam = textField1.getText().toLowerCase();
            }
        });
        textField2.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                super.keyReleased(e);
                achterNaam = textField2.getText().toLowerCase();
            }
        });
        OKButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                System.out.println(gebruikas); // is empty
                returnInputGebruiker();
            }
        });
    }
    Gebruikers g = new Gebruikers();
    ArrayList<Gebruiker> gebruikas = g.getGebruikers();
    
    public void worksFine() {
        System.out.println(gebruikas);//works fine on its own
    }

    public void returnInputGebruiker(){

        System.out.println(gebruikas);// is empty
    }

    public void run(JFrame parent) {
        JFrame frame = new JFrame();
        frame.setContentPane(panel1);
        frame.setTitle("persoon details");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        if (parent != null)
            frame.setLocationRelativeTo(parent);
        frame.setVisible(true);
    }
}

I tried putting the getter in different places but nothing seems to work.

CodePudding user response:

Have you tried to make "Gebruikers list" static and access it using the class name in the listener?

  • Related