Using keypad to move a circle at angles in java

后端 未结 2 1982
自闭症患者
自闭症患者 2021-01-17 02:40

So I have an application that successfully moves a ball (ellipse) left, right, up, or down depending on which button of the keypad is being pressed. However, I\'m having tro

2条回答
  •  鱼传尺愫
    2021-01-17 03:18

    Change your KeyClickListener to and observe the magic! then checkout this http://zetcode.com/tutorials/javagamestutorial/movingsprites/

        class KeyClickListener implements KeyListener, Runnable
        {
            private boolean moveLeft, moveRight, moveUp, moveDown;
            private Thread runThread;
            public KeyClickListener() {
                moveLeft = moveRight = moveUp = moveDown = false;
                runThread = new Thread(this);
                runThread.start();
            } 
            public void keyPressed(KeyEvent e) {assessKeycodes(e, true);}
            public void keyReleased(KeyEvent e){assessKeycodes(e, false);}
            public void keyTyped(KeyEvent e){}
    
            private void assessKeycodes(KeyEvent e, boolean setTo) {
                switch(e.getKeyCode()) {
                    case KeyEvent.VK_DOWN:
                        moveDown = setTo;
                        break;
                    case KeyEvent.VK_UP:
                        moveDown = setTo;
                        break;
                    case KeyEvent.VK_LEFT:
                        moveDown = setTo;
                        break;
                    case KeyEvent.VK_RIGHT:
                        moveDown = setTo;
                        break;
                }
            }
    
            public void run() {
                while(true) {
                    if (moveDown)
                            component.moveCircle(1);
                    if (moveUp)
                            component.moveCircle(2);
                    if (moveRight)
                            component.moveCircle(3);
                    if (moveLeft)
                            component.moveCircle(5);
                }
            }
        }
    

提交回复
热议问题