JavaFX并发任务设置状态 [英] JavaFX concurrent task setting state
问题描述
我正在为我的应用程序创建UI,该UI与其他平台的版本共享一个核心模块.在JavaFX中,我尝试使用 Task
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.
这就是我想要做的. user
变量包含一个类的实例,该类执行 xmlrpc 请求:
This is what I'm trying to do. The user
variable holds an instance of a class which performs xmlrpc requests:
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();
}
};
}
在我的UI线程中,我希望能够执行以下操作来更新图形用户界面:
In my UI Thread I want to be able to do something like this to update my graph UI:
loginTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
// perform an UI update here depending on the state t
}
});
我应该如何设置状态? 任务API 中没有执行此操作的操作.
How am I supposed to set the state? There is nothing that does that in the Task API.
推荐答案
Task
状态不适用于用户逻辑.引入它们来控制Task
流量.要将用户逻辑添加到Task
中,您需要使用result
概念.在您的情况下,您可能需要使用Task<Boolean>
,任务的结果将为TRUE
以获得正确的凭据,而FALSE
则获得不正确的信息:
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:
任务创建:
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;
}
};
}
开始该任务:
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();
这篇关于JavaFX并发任务设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!