java JavaFX 并发任务设置状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13935366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX concurrent task setting state
提问by Dreen
I am creating the UI for my application which shares a core module with versions for other platforms. In JavaFX, I'm trying to use Task
s to do things in the background, but I can't figure out how to update the Task state.
我正在为我的应用程序创建 UI,它与其他平台的版本共享一个核心模块。在 JavaFX 中,我尝试使用Task
s 在后台执行操作,但我不知道如何更新 Task 状态。
This is what I'm trying to do. The user
variable holds an instance of a class which performs xmlrpcrequests:
这就是我正在尝试做的。该user
变量包含一个执行xmlrpc请求的类的实例:
public Task<Integer> doLogin()
{
return new Task<Integer>() {
@Override
protected Integer call()
{
user.login();
if (!user.getIsAuthorized())
{
// set the state to FAILED
}
else
{
// set the state to SUCCEDED
}
user.remember();
}
};
}
In my UI Thread I want to be able to do something like this to update my graph UI:
在我的 UI 线程中,我希望能够执行以下操作来更新我的图形 UI:
loginTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
// perform an UI update here depending on the state t
}
});
How am I supposed to set the state? There is nothing that does that in the Task API.
我应该如何设置状态?在Task API 中没有任何东西可以做到这一点。
回答by Sergey Grinev
Task
states are not intended to be used for user logic. They are introduced to control Task
flow. To add user logic into Task
you need to use result
conception. In your case you may want to use Task<Boolean>
and result of your task will be TRUE
for correct credentials and FALSE
for incorrect:
Task
状态不打算用于用户逻辑。引入它们是为了控制Task
流量。要将用户逻辑添加到Task
您需要使用result
概念。在您的情况下,您可能想要使用Task<Boolean>
并且您的任务的结果将是TRUE
正确的凭据和FALSE
不正确的:
Task creation:
任务创建:
public Task<Boolean> doLogin() {
return new Task<Boolean>() {
@Override
protected Boolean call() {
Boolean result = null;
user.login();
if (!user.getIsAuthorized()) {
result = Boolean.FALSE;
} else {
result = Boolean.TRUE;
}
user.remember();
return result;
}
};
}
Starting that task:
开始那个任务:
final Task<Boolean> login = doLogin();
login.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
// This handler will be called if Task succesfully executed login code
// disregarding result of login operation
// and here we act according to result of login code
if (login.getValue()) {
System.out.println("Successful login");
} else {
System.out.println("Invalid login");
}
}
});
login.setOnFailed(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
// This handler will be called if exception occured during your task execution
// E.g. network or db connection exceptions
System.out.println("Connection error.");
}
});
new Thread(login).start();