Continuous movement with a single key press?

前端 未结 2 1314
一生所求
一生所求 2021-01-16 07:07

I\'m trying to make a program in java that involves making an object move constantly from a single key press. Think Pacman, where you press up once and Pacman continues to g

2条回答
  •  梦谈多话
    2021-01-16 07:52

    You need to process the move in a separate thread. I.e.:

    public class Pacman implements Runnable
    {
        public void run(){
            //moving code, i.e. in a while loop
    
            //every move will notify the EDT:
            SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                    //update the Swing here - i.e. move Pacman
                }
            }
        }
    
        public void startMoving(){
            new Thread(this).start();
        }
    
        //more methods to set speed, direction, etc...
    }
    

    Then you keep a reference to an instance of Pacman class in your Gui class and respond to various key presses by changing pacman's parameters:

    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            pacman.newDirection(LEFT); //for exmaple, enum with direction LEFT, RIGHT, UP, DOWN...
        }
        //etc... more logic
    }
    

提交回复
热议问题