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

时间:2015-03-12 18:10:24

标签: java javafx

我试图通过在单独的线程上完成工作并返回所需的对象来更改JavaFX中的GUI。但是,在完成工作并触发task.setOnSucceeded()后,我尝试检索创建的对象并获取错误"不兼容的类型:无法将对象转换为类型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()); }
    }
});

3 个答案:

答案 0 :(得分:3)

这是因为task.get()返回了Object类型的值,但您尝试将其分配给v,即VideoScrollPane。您可以通过执行强制转换来防止错误,如此

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

请注意,如果task.get()返回的内容不是VideoScrollPane,那么您将获得ClassCastException

如果您想完全避免此问题,请考虑通过包含泛型参数的类型来修复task的声明。您可以将其更改为,

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

这样,task.get()现在会返回VideoScollPane,您不会需要演员。

答案 1 :(得分:2)

您已正确声明Task。你需要

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

答案 2 :(得分:-1)

task.get();的返回类型为Object而不是VideoScrollPane ,请将其更改为:

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