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

查看:1991
本文介绍了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()); }
    }
});


推荐答案

这是因为任务.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.

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

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>() {

这样,任务。 get()现在将返回 VideoScollPane ,您将不需要演员。

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

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

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