JavaFx异常: Not on FX application thread; currentThread = Timer-0

我的定时器任务中有两个控件:

@FXML TextArea Display;
@FXML Label Label_Display;

执行下方代码会抛出:Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0

Timer_task1 = new Timer();
Timer_task1.schedule(new TimerTask(){
    int count = 0;
    @Override
    public void run(){
        if (TCP_IP_IsConnect){
            count += 1;
            System.out.println("Timer1!" + count);
            Label_Display.setText(String.format("count=%s", count));//出错之处:Not on FX         application thread; currentThread = Timer-0
            Display.setText(String.format("count=%s", count));
            //JOptionPane.showMessageDialog(null, "警告提示框"+count, "Title", JOptionPane.WARNING_MESSAGE);
        }
    }
},0,500);

 让人百思不得解的是,这俩都是控件,为什么注释掉上面代码中的

Label_Display.setText(String.format("count=%s", count));

他就正常了呢?这不都是控件吗?

没关系,问题还是可以解的,参考这里:https://stackoverflow.com/questions/26916640/javafx-not-on-fx-application-thread-when-using-timer

按他的办法,更改为以下代码后,两个控件都可以使用了,难道这就是C#里面的那个this.Invoke吗?使用委托来解决跨线程。

Timer_task1 = new Timer();
Timer_task1.scheduleAtFixedRate(new TimerTask(){
    int count = 0;
    @Override
    public void run(){
        Platform.runLater(() ->{
            if (TCP_IP_IsConnect){
                count += 1;
                System.out.println("Timer1!" + count);
                Label_Display.setText(String.format("count=%s", count));
                Display.setText(String.format("count=%s", count));
                //JOptionPane.showMessageDialog(null, "警告提示框"+count, "Title", JOptionPane.WARNING_MESSAGE);
            }
        });
    }
},0,500);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值