Dennis Lukas
Dennis Lukas

Reputation: 593

JavaFX Service/Task/Worker and automation

I am using IntelliJ IDEA. I have a "Clicker game" project that im working on because I want to learn java and practise a bit. The labels in my JavaFX window need to be updated constantly. The way I wanted to do this is through a Timer and TimerTask, but I read somewhere that this wasn't a good idea and that I'd rather use a Worker/Task/Service. Implementing this (calling my Update() method) works once, but results in a runtime error. I have no idea what I'm doing wrong, anyone that can help me?

The update method:

public void Update(){
    dollarlabel.setText(Double.toString(player.getDollars()));
    vaselineCost.setText(Double.toString(player.shop.vaseline.cost));
    bolCost.setText(Double.toString(player.shop.bol.cost));
    appleCost.setText(Double.toString(player.shop.apple.cost));
    duikenCost.setText(Double.toString(player.shop.duiken.cost));
}

The service:

public Service service = new Service() {
    @Override
    protected Task createTask() {
        Update();
        return null;
    }
};

The method that starts the service:

public void InitializeService(){
    service.start();
}

InitializeService is called on the press of a button. Ideally it is called at the start of the program but hey..one issue at a time right?

here is the error when I call on "InitializeService": http://pastebin.com/jrsVh23R

To clarify, I do not know where the null pointer exception comes from. I declared my variables before they are used i.e.:

public Label dollarlabel = new Label();
public Label vaselineCost = new Label();
public Label bolCost = new Label();
public Label duikenCost = new Label();
public Label appleCost = new Label();

anyone that knows what im doing wrong? thanks in advance.

Upvotes: 2

Views: 439

Answers (1)

Vaibhav G
Vaibhav G

Reputation: 647

Try something like this..

protected Task createTask() { 
return new Task<Void>() {
   protected String call() throws        Exception 
  {
       Update();
       return null; 
   }
 }; 
 }

Adapted from code fragment in this link

Regarding the start of service...

button.setOnAction(new EventHandler<ActionEvent>() 
{
  public void handle() 
  {
       // Call to initilaizeService() 
   } 
}) ;

For understanding eventhandlers I used this link

In the update method add this..

void update() 
{
      Platform.runLater (new Runnable () 
      {
            public void run () 
             {
                 //all calls to setText goes here 
            } 
     }) ;
 } 

Upvotes: 2

Related Questions