moving an image with arrows in JAVAFX


Question

Iam working on a small game here, and I am trying to move an image using right and left arrows.

The image has been declared as an ImageView as you will see in the attached code..

feel free to correct me as much as you want!!

package wordsfalling;

    import java.*; 
    import java.net.URL;  
    import java.util.*;
    import java.util.ResourceBundle; 
    import javafx.event.*; 
    import javafx.event.EventHandler; 
    import javafx.fxml.*; 
    import javafx.fxml.Initializable; 
    import javafx.scene.image.ImageView;
    import javafx.scene.input.KeyCode; 
    import javafx.scene.input.KeyEvent; 
    import javafx.scene.input.*; 
    import javafx.scene.*; 

/**  * FXML Controller class  * 
      * @author ad  */

      public class WordsFallingFXMLController implements Initializable {

        @FXML
        private ImageView bar;

       // char [] alphapet = "ABCDEFGHIKLMNOPQRSTUVWXYS".toCharArray();


        public void initialize(URL url, ResourceBundle rb) {



            bar.setOnKeyPressed(new EventHandler<KeyEvent>()
        {
            @Override
            public void handle(KeyEvent ke)
            {
                if (ke.getCode().equals(KeyCode.RIGHT))
                {
                    bar.setX(4);
                }
            }
        }
            );

        } }

i have also treid to modify and implement this JavaFX: Moving image with arrow keys and spacebar

but it didnt work !!

any suggestions ?

thanks in advance

1
2
5/23/2017 12:16:44 PM

Quick Fix

If you check with a debugger, the line bar.setX(4); is never executed even on key press. The image view never receives the KeyEvent because it has not received focus. Hence, if you add the line image.setFocusTraversable(true); after setting up your event handler, then your problem will be “fixed”:

public class WordsFallingFXMLController implements Initializable {   
    @FXML
    private ImageView image;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        assert image != null : "fx:id=\"image\" was not injected: check your FXML file 'FXMLDocument.fxml'.";
        image.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.RIGHT)) {
                    image.setX(4);
                }
            }
        });
        image.setFocusTraversable(true);
    }
}

Longer Fix

However, if you are trying to move an image view to the right, the line bar.setX(4); is not exactly the best way to go, as it only moves the image 4px to the right of (0,0), and thus even if you press the right arrow key again, the image will not move. Moreover, it is usually a good idea to separate the model from the view. What I mean by this is that you do not want to be directly manipulating the image view. Instead you should set up an object (model) that stores integer values for the image’s x and y coordinate. The key events should modify the x and y coordinates of the model. Then you should update the image view to reflect the model’s new position.

Minimal Refactor

Ideally, you want the move the model to its own class but here is a minimal example that does what you have requested through the Controller.

public class FXMLDocumentController implements Initializable {

    @FXML
    private ImageView image; 
    int imageX = 0;
    int imageY = 0;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        image.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent key) {
                if (key.getCode().equals(KeyCode.RIGHT)) {
                    imageX += 5;
                } else if (key.getCode().equals(KeyCode.LEFT)) {
                    imageX -= 5;
                }
                updateImageView();
            }

            private void updateImageView() {
                image.setX(imageX);
                image.setY(imageY);
            }
        });
        image.setFocusTraversable(true);
    }
}

Final Comment

Additionally, when you post code on SO, it is often a good idea to format your code. If you use an IDE such as Netbeans or Eclipse, there should be an option to automatically format the code through the menu bar at the top. In general, people will be more inclined to help when they see formatted code.

3
5/20/2014 1:14:25 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon