JComboBox循环向上遍历向下箭头键

时间:2018-05-17 11:53:09

标签: jcombobox traversal keyevent 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);
        }
     }
  });

1 个答案:

答案 0 :(得分:0)

我们需要在设置索引后使用该事件。

e.consume()

解决!!!