java - JavaFX return value from task -
i new javafx programmer , having issue getting result javafx task. want object task. here simple code.
public class myclass { public static void main(string[] args) { final mytask task = new mytask(); thread th = new thread(task); th.start(); myobject result; task.addeventhandler(workerstateevent.worker_state_succeeded, new eventhandler<workerstateevent>() { @override public void handle(workerstateevent t) { result = task.getvalue(); } }); } } public class mytask extends task<myobject> { myobject object; @override protected myobject call() throws exception { // basic processing return object; } }
i error result object should final , if cant value in result object. have tried searching on forum , google , couldn't find answer. appreciated. thanks.
you can't reassign value of local variable inside anonymous inner class (or lambda expression). issue don't know when task going finish, don't know when handler going invoked. method in (the main
method in example) may have finished then, local variable out of scope. doesn't make sense assign value it, won't ever able access value.
you can, however, assign value instance variable (or, in case, static variable). if move declaration of result
outside of main
method, work.
typically, though when task completes, want process results (updating ui). like:
task.addeventhandler(workerstateevent.worker_state_succeeded, new eventhandler<workerstateevent>() { @override public void handle(workerstateevent t) { myobject result = task.getvalue(); // result } });
as mentioned in 1 of comments (and aside), should register handler before start thread, otherwise cannot assured handler registered before thread completes.
Comments
Post a Comment