使用 KeyListener 时 Java JList 报告不正确的索引

问题描述 投票:0回答:1

我想了解为什么当 KeyPressedListener 触发向上和向下按键事件时,此 JLIST 对象的打印列表索引与突出显示的行不同步,以及如何解决该问题

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JList;
import java.awt.BorderLayout;

public class ListTest
{

    private JFrame frame;
    private String[] values = new String[] {"Line 0", "Line 1", "Line 2", "Line 3"};

    public static void main(String[] args)
    {
        ListTest window = new ListTest();
        window.frame.setVisible(true);
    }
    public ListTest()
    {

        frame = new JFrame();
        frame.setBounds(100, 100, 136, 153);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JList<String> list = new JList<String>(values);
        frame.getContentPane().add(list, BorderLayout.CENTER);
        list.setSelectedIndex(0);
        list.addKeyListener(new KeyListener()
        {
            @Override
            public void keyReleased(KeyEvent arg0){}
            @Override
            public void keyTyped(KeyEvent arg0){}
            @Override
            public void keyPressed(KeyEvent e)
            {
                int code = e.getKeyCode();

                switch( code ) 
                { 
                case KeyEvent.VK_UP:
                    System.out.println("UP " + list.getSelectedIndex());
                    break;
                case KeyEvent.VK_DOWN:
                    System.out.println("DOWN " + list.getSelectedIndex());
                    break;
                }
            }
        });
    }
}
java keylistener
1个回答
3
投票

因为

keyPressed
事件将返回之前的选择。

只需获取

keyReleased
事件的输出就可以了。

public void keyReleased(KeyEvent arg0) {
    int code = arg0.getKeyCode();

    switch (code) {
        case KeyEvent.VK_UP:
            System.out.println("UP " + list.getSelectedIndex());
            break;
        case KeyEvent.VK_DOWN:
            System.out.println("DOWN " + list.getSelectedIndex());
            break;
    }
}

这是对关键事件的更好解释:

keyPressed()
:当按键按下时

keyReleased()
:当按键出现时

keyTyped()
:发送该键代表的unicode字符时 通过键盘到系统输入

当按键出现时,会选择

JList
中的项目。当
keyReleased
被触发时,
JList
中的下一个项目将已被选择。但
keyPressed
事件会在选择发生之前触发。

© www.soinside.com 2019 - 2024. All rights reserved.