JavaFX不在FX应用程序线程上

时间:2017-01-05 20:40:59

标签: java runnable

因此,我通过使用Runnable进行多线程处理,每隔x秒就通过一项任务让我的应用程序检查客户。所以我将ScheduledExecutorService塞进了我的控制器类,新的线程被调用了,而且所有的花花公子都是花花公子,但每当我尝试发出警报时,我都会遇到IllegalStateException。

班级:

public class Line implements Runnable
{

    public Line()
    {
        System.out.println("I'm made");
    }

    @Override
    public void run()
    {
        System.out.println("I've started");
        try
        {
            Alert alert = new Alert(AlertType.ERROR, "Line is empty");
            alert.setTitle("Error");
            alert.setHeaderText("Line empty");
            System.out.println("I've ended");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

我尝试将整个run()函数放入Platform.runLater中,如下所示:

Platform.runLater(new Runnable() {
          @Override
            public void run()
            {
                System.out.println("I've started");
                try
                {
                    Alert alert = new Alert(AlertType.ERROR, "Line is empty");
                    alert.setTitle("Error");
                    alert.setHeaderText("Line empty");
                    System.out.println("I've ended");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });

然后Runnable抱怨没有跑()。

任何人都知道如何做到这一点?必须通过ScheduledExecutorService每x秒调用一次代码,并且必须在run()函数内进行警报。

1 个答案:

答案 0 :(得分:1)

你在两个不同的Runnable之间感到困惑。您的Line实现了Runnable,因此必须实现由调度程序执行的run。但是考虑到你想要将UI工作转发回FX线程,你需要传递另一个Runnable实现,la:

 public class Line implements Runnable
    {

        public Line()
        {
            System.out.println("I'm made");
        }

    @Override
    public void run()
    {
      Platform.runLater(new Runnable() {
            @Override
            public void run()
            {
              System.out.println("I've started");
              try
              {
                 Alert alert = new Alert(AlertType.ERROR, "Line is empty");
                 alert.setTitle("Error");
                 alert.setHeaderText("Line empty");
                 System.out.println("I've ended");
              } catch (Exception e) {
                e.printStackTrace();
              }
          }});
     }
}