因此,我收到了一项任务,让我的应用程序通过使用 Runnable 的多线程每 x 秒检查一次客户。因此,我将 ScheduledExecutorService 塞入我的 Controller 类中,然后新线程被调用,这一切都很好,但每当我尝试发出警报时,我都会收到 IllegalStateException。
类(class):
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 提示没有 run()。
有人知道如何做到这一点吗?该代码必须每 x 秒通过 ScheduledExecutorService 调用一次,并且必须在 run() 函数内发出警报。
最佳答案
您对两个不同的 Runnable
感到困惑。您的 Line 实现了 Runnable,因此必须实现 run,它将由调度程序执行。但考虑到您想要将 UI 工作中继回 FX 线程,您需要将其传递给另一个 Runnable 实现,例如:
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();
}
}});
}
}
关于JavaFX 不在 FX 应用程序线程上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494302/