Dhruva Sharma
Dhruva Sharma

Reputation: 1

Having Trouble in Callin the ArrayList

So I am making a java program that quizzes students on the capital of the USA states.(I am fairly new to JAVA) Okay guys so here is part of my program:

class SetUpButtonActionListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e) 
    {

        for(int i=0; i < state.size(); i++)
        {
            question = (String)(state.get(i));
            //i++;
            countryName.setText(question);
        }

    }

}

The problem is when I am trying to call the ArrayList one by one in the SetUpButtonActionListener class. It runs fine, but when I click on the New Problem button its supposed to show each one state and ask the user for the capital(haven't gotten to this part yet). However, when I click the button it doesn't show up with anything. I am not really to sure what I am doing wrong. Any help would be awesome!

Upvotes: 0

Views: 55

Answers (3)

elias
elias

Reputation: 15480

First of all, you need to call stateName() to fill the array.

Second, this way you did, every time the button is clicked, the method actionPerformed is called, and the loop runs with all the values of the array, always finishing getting the last value.

What you need is to maintain a value pointing to the next value of the array, so this way, every time you click the button, only the next item is got.

class SetUpButtonActionListener implements ActionListener{
    int currentIndex = 0;
    public void actionPerformed(ActionEvent e) {
        //verify if the index is inside the array (reseting it if not)
        //get the value
        //increase the index
    }
}

Upvotes: 0

Ziker
Ziker

Reputation: 906

you should call filling method of your list in the constructor

public QuizPanel()
{
            stateName()
            setUpButton = new JButton("New problem!");
            add(setUpButton);
            setUpButton.addActionListener(new SetUpButtonActionListener());
            ...
             }

Upvotes: 0

user180100
user180100

Reputation:

state is and will remain empty until you call stateName(). This explain the observed behavior.

You probably want to add a call to stateName() at the beginning of your constructor.

Upvotes: 3

Related Questions