JavaFX Service/Task/Worker 和自动化

JavaFX Service/Task/Worker and automation

我正在使用 IntelliJ IDEA。 我有一个正在处理的 "Clicker game" 项目,因为我想学习 java 并进行一些练习。我的 JavaFX window 中的标签需要不断更新。我想这样做的方法是通过 Timer 和 TimerTask,但我在某处读到这不是一个好主意,我宁愿使用 Worker/Task/Service。实现它(调用我的 Update() 方法)只工作一次,但会导致运行时错误。我不知道我做错了什么,有人可以帮助我吗?

更新方法:

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

服务:

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

启动服务的方法:

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

InitializeService 在按下按钮时被调用。理想情况下,它在程序开始时被调用,但是嘿..一次一个问题对吗?

这是我调用 "InitializeService" 时的错误:http://pastebin.com/jrsVh23R

澄清一下,我不知道空指针异常是从哪里来的。我在使用变量之前声明了它们,即:

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

有人知道我做错了什么吗?提前致谢。

试试这样的..

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

改编自此 link

中的代码片段

关于服务开始...

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

为了理解事件处理程序,我使用了这个 link

在更新方法中添加这个..

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