javafx - 将参数传递给扩展服务类 Java 的类
问题描述
我想知道是否有一种方法可以将参数传递给从 Javafx 并发包中扩展 Service 类的类。我希望 ProteinariumThread 接受如下所示的 ClusterID 之类的字符串参数:
public class ProteinariumThread extends Service<String>{
String ClusterID = "q";
@Override
protected Task<String> createTask(){
return new Task<String>() {
@Override
protected String call() throws Exception {
updateMessage("Running Proteinarium");
System.out.println("Asleep");
ProteinariumRun.PRun(ClusterID);
System.out.println("Woke Up");
String woke = "Woke Up";
return woke;
}
};
}
}
目前为了运行这个后台任务,我使用以下代码:
final ProteinariumThread service = new ProteinariumThread();
service.start();
但是,这不允许我接受 String 参数。有没有办法让 service.start() 能够接受字符串参数,以便字符串变量 ClusterID 可以来自 ProteinariumThread 类的外部?
final ProteinariumThread service = new ProteinariumThread();
service.start(ClusterID);
解决方案
您只需要为您的服务类提供一个接受必要参数的构造函数和/或方法。由于服务是可重用的,因此最好通过公开属性来允许在服务的整个生命周期中进行配置:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
public class ProteinariumService extends Service<String> {
private final StringProperty clusterId = new SimpleStringProperty(this, "clusterId");
public final void setClusterId(String clusterId) { this.clusterId.set(clusterId); }
public final String getClusterId() { return clusterId.get(); }
public final StringProperty clusterIdProperty() { return clusterId; }
public ProteinariumService() {}
public ProteinariumService(String clusterId) {
setClusterId(clusterId);
}
@Override
protected Task<String> createTask() {
return new Task<>() {
final String clusterId = getClusterId(); // cache configuration
@Override
protected String call() throws Exception {
...
}
};
}
}
将所需状态从服务复制到任务很重要,因为任务是在后台线程上执行的。
然后,当您需要更改集群 ID 时,您只需执行以下操作:
// or bind the property to something in the UI (e.g. a TextField)
theService.setClusterId(newClusterId);
theService.start();
如果你真的希望能够在一行中做到这一点,你总是可以start
在你的服务类中定义一个重载:
public void start(String clusterId) {
setClusterId(clusterId):
start();
}
推荐阅读
- android - Android:如何使用位图顶部捕获 imageView
- python - 条件装饰器实现
- html - Background image not scaling on smaller screen size
- c++ - 如何在 C++ 中将 RAND_bytes() 返回值转换为字符串
- ios - 推送视图控制器时应用程序冻结
- oracle - Oracle 表单排序记录
- c - 双向链表的删除算法
- java - 使用 ID 引用将 JSON 实体反序列化为 POJO
- regex - Aggregation count of mail domains using elastisearch
- postgresql - JOOQ: get difference between two dates in minutes