我正在尝试抓取谷歌财经。 getStockInfoFromGoogle
方法将两个字符串:(1) 股票名称和 (2) 收盘价存储到 ObservableList<String>
中。 。这很好用。
然后我尝试使用 ScheduledService
在后台运行此方法因此,priceService
应该返回 ObservableList<String>
。
当我尝试检索 ObservableList<String>
时出现问题来自 ScheduledService 方法,因为我无法从列表中单独提取字符串并将它们与 lastValueProperty()
相关联并将其绑定(bind)到 openingPrice 属性。
我该如何解决这个问题? (我想在这里保留lastValueProperty()
)。
public class Trade{
private final ReadOnlyStringWrapper stockName;
private final ReadOnlyDoubleWrapper closingPrice;
private final ScheduledService<ObservableList<String>> priceService = new ScheduledService<ObservableList<String>>() {
@Override
public Task<ObservableList<String>> createTask(){
return new Task<ObservableList<String>>() {
@Override
public Number call() throws InterruptedException, IOException {
return getStockInfoFromGoogle();
}
};
}
};
// constructor
public Trade(){
priceService.setPeriod(Duration.seconds(100));
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
this.closingPrice = new ReadOnlyDoubleWrapper(0);
this.stockName = new ReadOnlyStringWrapper("");
// this is the part where things goes wrong for the two properties below
this.closingPrice.bind(Double.parseDouble(priceService.lastValueProperty().get().get(1)));
this.stockName.bind(priceService.lastValueProperty().get().get(0));
}
public ObservableList<String> getStockInfoFromGoogle() throws InterruptedException, IOException{
ObservableList<String> output = FXCollections.observableArrayList();
// do some web scraping
output.add(googleStockName);
output.add(googleClosingPrice);
return output;
}
最佳答案
你的设计看起来很困惑,如 Trade
类似乎既封装了交易(名称和价格),又似乎管理服务(仅更新单个交易?)。
无论如何,使用 List
这不是正确的方法,您应该创建一个类来封装从服务返回的数据:
class TradeInfo {
private final String name ;
private final double price ;
public TradeInfo(String name, double price) {
this.name = name ;
this.price = price ;
}
public String getName() {
return name ;
}
public double getPrice() {
return price ;
}
}
现在让你的ScheduledService
一个ScheduledService<TradeInfo>
等等,你可以这样做
public TradeInfo getStockInfoFromGoogle() throws InterruptedException, IOException{
// do some web scraping
return new TradeInfo(googleStockName, googleClosingPrice);
}
现在创建绑定(bind):
this.closingPrice.bind(Bindings.createDoubleBinding(() ->
priceService.getLastValue().getPrice(),
priceService.lastValueProperty());
this.stockName.bind(Bindings.createStringBinding(() ->
priceService.getLastValue().getName(),
priceService.lastValueProperty());
(您可能需要处理 priceService.getLastValue()
为 null
的情况。)
关于Javafx:从 ScheduledService 检索 observableList 各个元素并将它们分别绑定(bind)到不同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32635944/