How to switch between the next element and the previous element of a Listiterator with just one click?

Asked

Viewed 944 times

5

I have a list of words stored in my variable listaPalavra already initialized with values, of type ArrayList<T>:

listaPalavra.add("Palavra 1");
listaPalavra.add("Palavra 2");
listaPalavra.add("Palavra 3");
listaPalavra.add("Palavra 4");
listaPalavra.add("Palavra 5");

from this list of words I get the list of itarator as follows:

listIterator = listaPalavra.listIterator();

I plan to use my iterator list listIterator to navigate the elements using the methods next() and previous() and display them on the form.

This is the form:

Formulario para nevegar nos entre os itens

Navigation is done by buttons Previous and Next as follows:

Button routine Previous:

private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {
    if (listIterator.hasPrevious()) {
        lbValor.setText(listIterator.previous());
    }
}

Button routine Next:

private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {
    if (listIterator.hasNext()) {
        lbValor.setText(listIterator.next());
    }        
}

Complete code of the form I created as an example to be reproduced by you:

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class MainFrameExemplo extends javax.swing.JFrame {    
    List<String> listaPalavra = new ArrayList<>();        
    ListIterator<String> listIterator;
    
    public MainFrameExemplo() {
        initComponents();
        
        listaPalavra.add("Palavra 1");
        listaPalavra.add("Palavra 2");
        listaPalavra.add("Palavra 3");
        listaPalavra.add("Palavra 4");
        listaPalavra.add("Palavra 5");

        listIterator = listaPalavra.listIterator();
        
        String primeiroElemento = listaPalavra.get(0);
        
        lbValor.setText(primeiroElemento);
    }
        
    //Método para inicializar os componentes visuais, o NetBeans gera para você.        
    private void initComponents() {
    ...
    }

    private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if (listIterator.hasPrevious()) {
            lbValor.setText(listIterator.previous());
        }
    }                                           

    private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if (listIterator.hasNext()) {
            lbValor.setText(listIterator.next());
        }        
    }                                          
        
    public static void main(String args[]) {                
        java.awt.EventQueue.invokeLater(() -> 
        {
            new MainFrameExemplo().setVisible(true);
        });
    }
    
    private javax.swing.JButton btnAnterior;
    private javax.swing.JButton btnProximo;
    private javax.swing.JLabel lbValor;    
}

My problem

Every time I will switch between the next element and the previous one I I have to double-click the button, as much as on the button Next as in the button Previous. I would like to switch between the next and previous elements by just clicking the button.

See this gif that shows my problem:

Gif do problema

How could I solve this problem?

  • Interesting doubt that, +1 :) then read the answer

1 answer

6


Hello, young man!

Man, that’s an easier question to explain by drawing, but I’ll try by text.

The iterator has as reference the list in question and will also have as reference the current item. When you arrive at one of the extremes, for example in the "Word 5" item, when you give a next, it automatically goes to the next item. It turns out that this item does not exist, but the list reference pointer moved. So when you give a listIterator.previous() it will keep the value "Word 5" because it was outside the range of the list, then it goes back to the last item of the list.

The secret to fix is to check if you have reached any of these extremes and already "rewind" or "forward" to the end item.

private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {                                            
    if (listIterator.hasPrevious()) {
        String previous = listIterator.previous();
        lbValor.setText(previous);
        if ( !listIterator.hasPrevious()  ) listIterator.next();
    }
}                                           

private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if ( listIterator.hasNext()  ) {
        lbValor.setText(listIterator.next());
        if ( !listIterator.hasNext()  ) listIterator.previous();
    }        
}  

Another change is the moment the frame is instantiated. In it you are taking item 0 of the vector. The cool thing is that you already use the iterator itself:

    listIterator = listaPalavra.listIterator();
    String primeiroElemento = listIterator.next();
    lbValor.setText(primeiroElemento);

Greetings!

Edition 01

After placing the gif, it was noted that it was necessary to take another direction and use the index to access the message.

In main, it is better to use like this

   listIterator = listaPalavra.listIterator();
   listIterator.next();
   String primeiroElemento = listaPalavra.get(listIterator.nextIndex() - 1);
   lbValor.setText(primeiroElemento);

And in the listiners so:

private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {                                            
    if (listIterator.hasPrevious() && listIterator.previousIndex() > 0) {
        listIterator.previous();
        lbValor.setText( listaPalavra.get(listIterator.nextIndex() - 1) );
    }
}                                           

private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if ( listIterator.hasNext()  ) {
        listIterator.next();
        lbValor.setText( listaPalavra.get(listIterator.nextIndex() - 1) );
    }        

}      
  • Hello, the border issue worked, however, if I have in the palavra 3 and want to go back to the previous one which is the palavra 2 I have to double-click the Previous button.

  • Really? Weird dude, my implementation here was good. Check it out: http://dev.coppieters.com.br/exemplos/MainFrameExemplo.java

  • Yes, I used your implementation, when I will click on the next one and then click on Previous it does not change, I have to click again on the previous one to change the value.

  • I put a gif in the question.

  • @Denercarvalho, cara I put the following line on the two guys dealing with the event: System.out.println("Next Index:" + listIterator.nextIndex() + " - Previous Index:" + listIterator.previousIndex() ); When changes the direction of the vector, It seems that it gets lost to return the value, but not the information. When switching to take the Dice, and putting a previous validation in the rewind, it works. .

  • 1

    It worked here :D

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.