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:
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:
How could I solve this problem?
Interesting doubt that, +1 :) then read the answer
– user28595