JList 在Jpanel切换后 不能直接用键盘操作?

JList 在Jpanel切换后 不能直接用键盘操作,都需要用鼠标点击一下jList组件,然后jList才能用键盘上下键操作。(如何不用鼠标点击,切换后直接可以用键盘操作?)

代码如下:

public class JlistTest {

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setSize(500,500);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭退出
        jFrame.setLocationRelativeTo(null);// 设置 JFrame 窗口置于屏幕的中央

        JPanel jPanel1 = new JPanel(null){
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                g2.setPaint(Color.white);// 背景颜色
                g2.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        jPanel1.setPreferredSize(new Dimension(500,500));
        jFrame.add(jPanel1);

        jFrame.setVisible(true);

        try {
            Thread.sleep(3000);// 睡眠3秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        JPanel jPanel2 = new JPanel(); // 切换的jPanel2
        JList<String> jList = new JList<>(new String[]{"aaa","bbb","ccc","ddd"});
        jList.setBackground(Color.black);
        jList.setForeground(Color.white);
        jPanel2.add(jList);
        jFrame.remove(jPanel1);// 移除 jPanel1
        jFrame.add(jPanel2);// 切换成 jPanel2

        jFrame.revalidate();
        jFrame.repaint();
    }
}

 

百度知道已回答