我的代码有问题。我尝试做蛇游戏,但我停在不断移动到绘制面板的ActionMap中的位置。我试图在循环中使用drawPanel.repaint,但仅在到达末尾时才显示,但我希望所有动作都在ActionMap中给出。
我该怎么办?还是有人有其他解决方案?

    DrawPanel drawPanel = new DrawPanel();

    public Snake(){
        InputMap inputMap = drawPanel.getInputMap();//JPanel.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = drawPanel.getActionMap();
        inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
        actionMap.put("rightAction", rightAction);
        inputMap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
        actionMap.put("leftAction", leftAction);
        inputMap.put(KeyStroke.getKeyStroke("UP"), "upAction");
        actionMap.put("upAction", upAction);
        inputMap.put(KeyStroke.getKeyStroke("DOWN"), "downAction");
        actionMap.put("downAction", downAction);

        add(drawPanel);
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private class DrawPanel extends JPanel {

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.GRAY);
                    g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.GREEN);
            g.fillRect(x, y, 10, 10);
        }
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }
    }

    Action downAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            while (y<390)
            {
                y +=+10;
                drawPanel.repaint();
            }
          /*  if (y<390)
                y +=+10;
            else
                y = 390;
            drawPanel.repaint();
            */
          }
    };

    Action upAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            if (y>0)
                y -=10;
            else
                y = 0;
            drawPanel.repaint();
        }
    };

      Action leftAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            if (x>0)
                x -=10;
            else
                x = 0;
            drawPanel.repaint();
        }
    };

    Action rightAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            if (x<390)
                x +=10;
            else
                x = 390;
            drawPanel.repaint();
        }
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new Snake();
            }
        });
    }
}

最佳答案

herehere所示,您可以在actionPerformed()Action中调用自己的ActionListener实例的javax.swing.Timer方法。您可以调整计时器的delay来调整动画的速度。

10-08 19:27