Search code examples
jcomboboxtraversalkeyeventarrow-keys

JComboBox circular traversal up down arrow keys


I have a question regarding JComboBox. I am trying to make a circular traversal using UP DOWN arrow keys. However when I reach the bottom after a down arrow key is pressed, I set the selected index to 0. But it reaches item index 1. Same goes for the other way. When at the top and the up key is pressed, the item before the final element is selected. Is there a way to fix this?

Thanks in advance.

public class ComboTest {

public static void main(String[] args){
  JFrame f = new JFrame("Java Swing Examples");
  final JComboBox c = new JComboBox();
  for ( int i = 0; i < 5 ; i++) {
     c.addItem(i+"");
  }

  f.getContentPane().add(c);
  f.pack();
  f.setMinimumSize(new Dimension(300,200));
  f.setPreferredSize(new Dimension(300,200));

  c.addKeyListener(new KeyListener()
  {
     public void keyTyped(KeyEvent e) { }

     public void keyReleased(KeyEvent e) {
        int index = c.getSelectedIndex();
        System.out.println("Released: "+index);
     }

     public void keyPressed(KeyEvent e) {

        int index = c.getSelectedIndex();
        System.out.println("Pressed: "+index);

        if(index == c.getItemCount()-1 && e.getKeyCode()==KeyEvent.DOWN) {
           c.setSelectedIndex(0);
        } else if (index == 0 && e.getKeyCode() == KeyEvent.VK_UP) {
           c.setSelectedIndex(c.getItemCount()-1);
        }
     }
  });

Solution

  • We need to consume the event after setting the index.

    e.consume()

    Solved!!!