I have a list of words stored in my listaPalavra
variable 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 itarator list as follows:
listIterator = listaPalavra.listIterator();
I intend to use my list of iterator listIterator
to navigate the elements using the next()
and previous()
methods and display them on the form.
This is the form:
NavigationisdonebythePreviousandNextbuttonsasfollows:
ButtonroutinePrevious:
privatevoidbtnAnteriorActionPerformed(java.awt.event.ActionEventevt){if(listIterator.hasPrevious()){lbValor.setText(listIterator.previous());}}
ButtonroutineNext:
privatevoidbtnProximoActionPerformed(java.awt.event.ActionEventevt){if(listIterator.hasNext()){lbValor.setText(listIterator.next());}}
CompletecodeoftheformIcreatedasanexampletobereproducedbyyou:
importjava.util.ArrayList;importjava.util.List;importjava.util.ListIterator;publicclassMainFrameExemploextendsjavax.swing.JFrame{List<String>listaPalavra=newArrayList<>();ListIterator<String>listIterator;publicMainFrameExemplo(){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 switch between the next element and the previous element I have to double-click the button as well as the Next button as in the 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 can I solve this problem?