0

My program is a game, and it requires sprites to be spawned every 2 seconds. And following is my code so far for the same:


    @Override
    public void run() {

        try {
            spawnSprite(300, 300, true);
        } catch(NullPointerException e){
            e.printStackTrace();
            System.exit(0);
        }
    }
    private void spawnSprite(float x, float y, Boolean isPea){

        String url;
        if(isPea)
            url = "/Assets/Pea.png";
        else
            url = "/Assets/Not_pea.png";

        Image image = new Image(getClass().getResourceAsStream(url));
        ImageView Im = new ImageView();
        Im.setImage(image);
        Im.setX(x);
        Im.setY(y);
        AP.getChildren().add(Im);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {   
        spawnSprite( 300, 300, true);
        Timer SpawnTimer = new Timer();
        TimerTask task= new Map_Controller();
        SpawnTimer.scheduleAtFixedRate(task, 1000L,2000L);
    }
}

However AP,getChildren.add(Im) in spawnSprite() throws a NullPointerException. I did find out that no exception is thrown if I call the function from initialize().

Any suggestions would be very helpful, Thanks!

DhruvU
  • 1
  • 1
  • a) Are you creating a new instance of your controller class there? If this is the case it's almost certainly one that has no connection with any scene whatsoever. b) you seem to use a background thread to modify the GUI. This must not be done as JavaFX expects all modifications to be happening on the JavaFX application thread. For "the javafx way of doing this", see https://stackoverflow.com/questions/9966136/javafx-periodic-background-task – fabian Nov 29 '19 at 12:42
  • @fabian, I'm not creating an instance of my controller class anywhere as of now. I will look into the link, Thanks a lot. – DhruvU Nov 29 '19 at 12:50
  • [mcve] please .. – kleopatra Nov 29 '19 at 13:04
  • `TimerTask task= new Map_Controller();` what does this do, if not creating a new instance of the controller. Your statement about the method working, if invoked from `initialize` indicates that your controller is also a `TimerTask`, at least if I correctly read between the lines. – fabian Nov 29 '19 at 13:23
  • @fabian, sorry I forgot about that line. But I did check that link you sent me and it has fixed the issue, thanks a lot! – DhruvU Nov 29 '19 at 14:00

0 Answers0