简体   繁体   中英

Switch statement , only using one case at a time

Im trying to translate a square 'p' 5 units left or right depending on what key has been pressed . The problem is that when 'right' or 'left' is pressed it will translate 5 units in that direction but when I press again I can't move and I have to press 'left' to move right again so I never get anywhere. Does anyone know why this is?

    Task PlyThread=new Task() {
        @Override
        protected Object call() throws Exception {
            myScene.setOnKeyPressed(event -> {
                switch (event.getCode()){
                    //case UP: p.setTranslateY(((p.getY())-5)) ; break;
                    case LEFT: p.setTranslateX(((p.getX())-5)) ; break;
                    case RIGHT: p.setTranslateX(((p.getX())+5)) ;break;


                }
            });

            return null;
        }
    };new Thread(PlyThread).start();

Ok, I assume that "Rectangle" is javafx.scene.shape.Rectangle . In this case setTranslateX() only modifies transformation matrix and does not change the rectangle coordinate X. Value of property X remains unchanged and next call to setTranslateX(getX()+5) does exactly the same job as the one before.

You need to work either with translations or with coordinates, ie either use setTranslateX() / getTranslateX() or setX() / getX() .

Both choices may have other consequences, beyond moving rectangle on the screen, but I have no experience with JavaFX, so unfortunately I cannot elaborate more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM