首页 > 其他分享 >定时器更新界面,线程报错

定时器更新界面,线程报错

时间:2024-06-09 09:34:08浏览次数:8  
标签:定时器 java import javafx Timer 线程 new 报错 stage

项目场景:

在javafx框架下使用线程更新UI的时候,出现无法正常更新UI。

问题代码如下:

package clock;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SimpleClock extends Application{

    public static void main(String[] args) {
        Application.launch();
    }
    public void start(Stage stage) {
        
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                
                
                        init(stage);
                        
                    
                });
            }
        }, 0, 1000); 
    
    }

    private void init(Stage stage){
        Calendar calendar = new GregorianCalendar();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        ClockPane cPane = new ClockPane(hour, minute, second);
        Scene scene = new Scene(cPane, 300, 300);
        stage.setTitle("Watch");
        stage.setScene(scene);
        stage.show();
    }

    
}

问题描述

运行程序之后,出现如下报错:

Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
        at [email protected]/com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:294)
        at [email protected]/com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:481)
        at [email protected]/javafx.stage.Stage.setScene(Stage.java:269)
        at clock.SimpleClock.init(SimpleClock.java:34)
        at clock.SimpleClock$1.run(SimpleClock.java:23)
        at java.base/java.util.TimerThread.mainLoop(Timer.java:571)
        at java.base/java.util.TimerThread.run(Timer.java:521)

原因分析:

checkFxUserThread

从出错日志看出checkFxUserThread这个方法在检查用户进程是否为UI线程,如果不是会抛出异常,这是因为为了使UI渲染不出现阻塞现象,不允许在子线程中进行UI操作。


解决方案:

可以使用javafx框架提供的runlater方法,实现切换到UI线程来执行更新UI的操作。

    public void start(Stage stage) {
        
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        init(stage);
                        
                    }
                });
            }
        }, 0, 1000); 
    
    }

标签:定时器,java,import,javafx,Timer,线程,new,报错,stage
From: https://blog.csdn.net/lanxingstar2011/article/details/139554779

相关文章

  • 在Ubuntu中进行PX4配置的过程中出现以下报错,且不能正常打开gazebo
    ......
  • 【报错解决】深度学习模型训练时cuda内存足够但测试时反而报错cuda out of memory
    报错描述报错的代码如下:model=reader(config=args,encoder=encoder)#初始化模型model.to('cuda')#把模型放到gpu上model.load_state_dict(torch.load(join(args.checkpoint_path,'best_ckpt_model1.pkl')))#加载模型参数model=torch.nn.DataParallel(model)#并行化......
  • 树莓派 linux安装PyBlueZ报错:fatal error: bluetooth/bluetooth.h: No such file or d
    IwanttobuildacfilebasedonBlueZbutseemsnobluetooth.hfileinmysystem.fatalerror:bluetooth/bluetooth.h:NosuchfileordirectoryIamsurethebluetoothdongleisrunningcorrectlyandIhavebuiltBluezsuccessfully.UpdateFormyca......
  • Python【cv2:读取图片时报错】
    写在前面:opencv库安装在终端用pipinstall安装opencv-python库建议使用国内清华源的镜像去安装,加参数-ihttps://pypi.tuna.tsinghua.edu.cn/simple代码如下:pipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simpleopencv-python报错一我一开始直接用cv2.imread(p......
  • centos7运行sysctl -p 命令报错sysctl: cannot stat /proc/sys/vm/max/map_count: No
    这个错误表明 sysctl-p 命令尝试重新加载系统参数时,无法访问 /proc/sys/vm/max/map_count 文件在CentOS7中,这个文件通常位于 /proc/sys/vm/max_map_count解决方法:确认你有足够的权限执行该命令。如果不是root用户,使用 sudo 前缀来运行命令:sudosysctl-p如果......
  • 创建线程池工具类
    线程池具有以下属性:核心线程数:CORE_POOL_SIZE最大线程数:MAX_POOL_SIZE线程保持活跃时间:KEEP_ALIVE_SECONDS时间单位:TimeUnit.MILLISECONDS任务队列:LinkedBlockingQueue,容量为QUEUE_CAPACITY线程工厂:为每个新线程设置名称前缀"lwc-pool-"和一个自增的编号拒绝策略:Thread......
  • docker拉取镜像报错Bad Request
    问题现象docker拉取镜像报错BadRequest。问题分析cat/etc/systemd/system/docker.service.d/http-proxy.conf1.1.1.1:80模拟错误的docker代理配置,错误的代理导致镜像拉取失败。解决问题注释代理配置。vim/etc/systemd/system/docker.service.d/http-proxy.conf重启d......
  • Django上传图片时ImageField的max_length报错
    我使用的版本是Django4.2,有一个模型里定义了ImageField,以下面这个为例:classExample(models.Model)image=models.ImageField(blank=True,upload_to=my_image_path,)当我上传图片的时候,django返回了这样一个错误:Ensurethisfilenam......
  • 利用线程池给客户端传文件
    主函数#include<func.h>#include"threadPool.h"#include"server.h"#defineEVENTSNUM100intpipefd[2];voidsigHandle(intsigno){printf("%dsignal\n",signo);intexitNum=1;write(pipefd[1],&exitN......
  • 265 Custom Exceptions(更容易定位报错内容具体是什么)
    优势CustomExceptions相比于ArgumentException/ArgumentNullException,更容易定位报错内容具体是什么,报错内容与具体业务相关。示例新建类库项目Exceptions,为Services/CRUDExample项目添加Exceptions项目引用Exceptions项目中添加InvalidPersonIdException.csnamespac......