JAVA不兼容类型:无法将对象转换为我的类型

JAVA不兼容类型:无法将对象转换为我的类型,java,javafx,Java,Javafx,我试图通过在一个单独的线程上进行工作并返回所需的对象来更改JavaFX中的GUI。但是,在完成工作并触发任务后,我尝试检索创建的对象,并出现错误“不兼容类型:对象无法转换为VideoScrollPane类型” 我认为这与原始类型有关,因为这是在侦听器中发生的,但环顾四周后,我找不到我想要的建议 任何能发光的都将不胜感激 Task task = new Task<VideoScrollPane>() { VideoScrollPane vsp; @Override pr

我试图通过在一个单独的线程上进行工作并返回所需的对象来更改JavaFX中的GUI。但是,在完成工作并触发任务后,我尝试检索创建的对象,并出现错误“不兼容类型:对象无法转换为VideoScrollPane类型”

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

任何能发光的都将不胜感激

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 Task=新任务(){
视频滚动窗格vsp;
@覆盖受保护的VideoScrollPane调用(){
试一试{
系统输出打印(“线程…”);
ExecutorService executor=Executors.newCachedThreadPool();
Future=executor.submit(new Callable()){
@覆盖公共VideoScrollPane调用(){
返回新的VideoScrollPane(mediaview、VboxCenter、用户名、项目);
}
});
vsp=future.get();
}catch(异常){System.out.println(异常.getMessage());}
返回vsp;
}
};
新线程(任务).start();
task.setOnSucceeded(新的EventHandler(){
@重写公共无效句柄(WorkerStateT事件){
系统输出打印项次(“完成”);
试一试{
//问题发生在哪里
VideoScrollPane v=task.get();
}catch(异常){System.out.println(异常.getMessage());}
}
});

这是因为
任务.get()
返回的值类型为
对象
,但您试图将其分配给v,v是一个
视频滚动窗格
。您可以通过执行强制转换来防止错误,如下所示

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

如果您想完全防止问题,请考虑通过使用泛型参数的类型来修复<代码>任务< /代码>的声明。你可以把它改成

Task<VideoScrollPane> task = new Task<VideoScrollPane>() {
Task Task=新任务(){

通过这种方式,
task.get()
现在将返回一个
VideoScollPane
,您不需要强制转换。

任务的返回类型。get();是
对象
而不是
视频滚动窗格
,将其更改为:

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

您的
任务声明不正确。您需要

Task<VideoScrollPane> task = new Task<VideoScrollPane>() { ... }
Task Task=new Task(){…}

当您说“获取错误”时我想你指的是编译错误而不是运行时错误。你试过强制转换它吗?是的,是编译错误,抱歉。与其使用不必要的强制转换,不如更正任务的声明。这样你就可以确保返回的实际对象是正确的类型。@James_D谢谢,我已经包含了一个关于它的说明!我已经更正了声明正如建议的那样。感谢您的帮助。事实并非如此。
Task
中继承自
FutureTask
的声明是
public V get()
。因此,错误的不是返回类型的赋值,而是
Task
实例的声明。