Home > Software design >  Adding a String in an ArrayList everytime a button is clicked
Adding a String in an ArrayList everytime a button is clicked

Time:12-13

I am new to java and I am trying to create a quiz app for my final project using java. I want to add the text inputted in the textField to my ArrayList everytime the button is clicked. I tried making it but the ArrayList only contains one element even after inputting a text many times. here is the code:

public class AddQuestions implements ActionListener {

    public ArrayList<String> questions;
    JLabel questionLabel = new JLabel();
    JTextField question = new JTextField();
    JButton addButton = new JButton();

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addButton){
            while(addButton == e.getSource()){
                String value = question.getText();
                questions = new ArrayList<>();
                questions.add(value);
                System.out.println(value);
                question.setText("");
                break;
            }
        }
        System.out.println(questions);
        System.out.println(questions.size());

    }
}

CodePudding user response:

Remove the while as it is unecessary, when the button is click actionPerformed is only called once.

Also in your statement: questions=new ArrayList<>(); inside actionPerformed you are always re-initializing the object questions to a new memory locations hence result in lost of values you have added in ArrayList questions object. I suggest you read more about java by reading Java Programming Joyce Farrell it is a great book for beginners. It has a ton of programming exercises for you to memorize java.

public class AddQuestions implements ActionListener {

    public ArrayList<String> questions=new ArrayList<>();
    JLabel questionLabel = new JLabel();
    JTextField question = new JTextField();
    JButton addButton = new JButton();

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addButton){
           
                String value = question.getText();
                questions.add(value);
                System.out.println(value);
                question.setText("");
               
            
        }
        System.out.println(questions);
        System.out.println(questions.size());

    }
}
  • Related