Fred
Fred

Reputation: 830

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();

Upvotes: 1

Views: 213

Answers (1)

uaraven
uaraven

Reputation: 1107

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, i.e. 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.

Upvotes: 3

Related Questions