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()); }
}
});
Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].
The most direct solution to convert a Java string to an integer is to use the parseInt method of the Integer class: int i = Integer. parseInt(myString); parseInt converts the String to an int , and throws a NumberFormatException if the string can't be converted to an int type.
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();
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>() {
This way, task.get()
will now return a VideoScollPane
, and you won't need a cast.
You have declared your Task
incorrectly. You need
Task<VideoScrollPane> task = new Task<VideoScrollPane>() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With