Iterating through List but it only shows last item

后端 未结 2 1281
暖寄归人
暖寄归人 2021-01-21 21:09

What I am trying to achieve is have one JLabel to display multiple items from a List.

I have defined the list as below but when I test the code

相关标签:
2条回答
  • 2021-01-21 21:49

    Your current code always overrides the current text in the JPanel, and it does that so fast, that you don't see it. Instead of using the Iterator, get the next item in the list by defining an int variable that gets incremented every press.
    The index variable is a public int in this example:

     jLabel1.setText(strings.get(index));
     if (index < strings.size()-1) 
            index++;
    

    No loops, that's everything needed in your method.

    0 讨论(0)
  • 2021-01-21 22:10

    In order to locate next string from collection, you need somehow know about current item.

    One approach is to store index (or iterator) in a field:

    List<String> strings=<...>
    // 1. store index    
    int sentenceIndex = 0; 
    // 2. store iterator. You could get ConcurrentModificationException if change list and then use iterator.
    Iterator<String> iterator = strings.getIterator();
    private void buttonpressActionPerformed() { 
    // 1. use index. 
    if (sentenceIndex < strings.size()-1) { // avoid IndexOutOfBoundException
      String nextSentence = strings.get(sentenceIndex++);
    }
    // 2. use iterator
    if (iterator.hasNext()) {
      String nextSentence = iterator.next();
    }
    

    But in fact you don't need to store something:

    // 3. calculate current index
    String currentSentence = jLabel1.getText();
    int currentIndex = strings.indexOf(currentSentence);
    int nextIndex = incrementIndex(currentIndex);
    String nextSentence = strings.get(nextIndex );
    

    Note that I suggest new method incrementIndex. In it you could add not only lenght check but also jumping from last element to the first or just random selecting.

    Each method has pro and contras:

    1. index require boundary checks

    2. iterator limits list updating

    3. index calcucaliton also require boundary checks and label1 should have correct initial value

      I would prefer storing index but it's your choice

    0 讨论(0)
提交回复
热议问题