JAVA 不兼容类型:对象无法转换为我的类型 [英] JAVA incompatible types: Object cannot be converted to my type

查看:27
本文介绍了JAVA 不兼容类型:对象无法转换为我的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过在单独的线程上进行工作并返回所需的对象来更改 JavaFX 中的 GUI.但是,在完成工作并触发 task.setOnSucceeded() 后,我尝试检索创建的对象并收到错误类型不兼容:对象无法转换为 VideoScrollPane 类型".

I'm trying to make changes to my GUI in JavaFX by doing the work on a separate thread and returning the object required. However, after doing the work and task.setOnSucceeded() is triggered I attempt to retrieve the created object and get the error "incompatible types: Object cannot be converted to type VideoScrollPane".

我认为这与原始类型有关,因为它在侦听器中正在发生,但环顾四周后我找不到我正在寻找的建议.

I think this has something to do with raw types as it's within the listener this is happening but after looking around I couldn't find the suggestions I was looking for.

任何可以发出的光都将不胜感激.

Any light that can be shed would be much appreciated.

Task task = new Task<VideoScrollPane>() {
    VideoScrollPane vsp;
    @Override protected VideoScrollPane call() {
        try {
            System.out.print("thread...");

            ExecutorService executor = Executors.newCachedThreadPool();
            Future<VideoScrollPane> future = executor.submit(new Callable<VideoScrollPane>() {
                @Override public VideoScrollPane call() {
                    return new VideoScrollPane(mediaview, vboxCentre, username, project);
                }
            });

            vsp = future.get();
        } catch(Exception exception) { System.out.println(exception.getMessage()); }

        return vsp;
    }
};
new Thread(task).start();

task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
    @Override public void handle(WorkerStateEvent t) {
        System.out.println("complete");

        try {

            //where the problem occurs
            VideoScrollPane v = task.get();     

        } catch(Exception exception) { System.out.println(exception.getMessage()); }
    }
});

推荐答案

这是因为 task.get() 正在返回 Object 类型的值,但是你'正在尝试将它分配给 v,这是一个 VideoScrollPane.您可以通过执行强制转换来防止错误,就像这样

This is because the task.get() is returning a value of type Object, but you're trying to assign it to v, which is a VideoScrollPane. You can prevent the error by doing a cast, like so

VideoScrollPane v = (VideoScrollPane)task.get();

请注意,如果 task.get() 返回的内容不是 VideoScrollPane,您将收到 ClassCastException.

Be warned, if task.get() returns something that isn't a VideoScrollPane, you'll get a ClassCastException.

但是,如果您想完全避免该问题,请考虑修复 task 的声明,通过包含泛型参数的类型.你可以把它改成,

If you want to prevent the problem entirely however, consider fixing the declaration of task, by including a type for the generic parameter. You could change it to,

Task<VideoScrollPane> task = new Task<VideoScrollPane>() {

这样,task.get() 现在将返回一个 VideoScollPane,并且您不需要演员表.

This way, task.get() will now return a VideoScollPane, and you won't need a cast.

这篇关于JAVA 不兼容类型:对象无法转换为我的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆