2

I would like to iterate through a list every time a button is pressed, using JButton, JTextField and event's ActionListener. So every time the "next" button is pressed the next item in the array should be displayed in a JTextField. I have already created the getters, setters and constructor, it's literally only the following piece I'm having trouble with.

@Override
     public void actionPerformed(ActionEvent evt){
     Object source = evt.getSource();

     String[] item = getThing();

     for(int i = 0; i < 3; i ++){
         String currentI = item[i];
     }
     if(source.equals(btnNxt)){
         txtDisplayField.setText(currentI);
     }
}

In the if statement I receive an error "Cannot find symbol", referring to currentI.

3 Answers 3

4

The currentI variable went out of scope at the end of the loop. You should declare it outside of the for loop.

By the way, the code still won't work properly, because you set the value to the last item of the array every time. You should step only once, and if you are at the last item, jump to the first one.

Sign up to request clarification or add additional context in comments.

Comments

1

You're initializing your currentI String within your for loop's scope.

The variable is therefore inaccessible outside your for loop.

Move your equality check and assignment inside the loop.

for(int i = 0; i < 3; i ++){
    String currentI = item[i];

    if(source.equals(btnNxt)){
        txtDisplayField.setText(currentI);
        // stop iteration as you already found a match
        break;
    }
}

Comments

0

I don't see why you need a for loop at all.

Simply :

int ctr = 0;
public void actionPerformed(ActionEvent evt){
  ctr++;
  if(ctr<item.length)
    txtDisplayField.setText(iter[ctr]);
}

That should solve your problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.