我想了解爲什麼當KeyPressedListener觸發上下按鍵事件時,此JLIST對象的打印列表索引與突出顯示的行不同步,以及如何解決問題Java JList在使用KeyListener時報告不正確的索引
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;
}
}
});
}
}
這種情況可能會引起學術界的興趣,但我覺得有必要指出,監聽JList選擇的更改的正確方法是使用[addListSelectionListener](https://docs.oracle.com/javase/8 /docs/api/javax/swing/JList.html#addListSelectionListener-javax.swing.event.ListSelectionListener-),因爲顯然箭頭鍵並不是改變選擇的唯一方法。 – VGR