JComboBox循环遍历上下方向键

JComboBox circular traversal up down arrow keys

我有一个关于 JComboBox 的问题。我正在尝试使用向上向下箭头键进行循环遍历。但是,当我按下向下箭头键到达底部时,我将所选索引设置为 0。但它到达了项目索引 1。另一种方式也是如此。当在顶部并按下向上键时,最后一个元素之前的项目被选中。有办法解决这个问题吗?

提前致谢。

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);
        }
     }
  });

设置索引后需要消费事件

e.consume()

已解决!!!