我正在尝试抓取Google财务。 getStockInfoFromGoogle方法存储两个字符串:(1)股票名称和(2)收盘价到ObservableList<String>中。这很好。

然后,我尝试使用ScheduledService在后台运行此方法,因此,priceService应该返回一个ObservableList<String>

当我尝试从ScheduledService方法检索ObservableList<String>时出现问题,因为我无法从列表中单独提取字符串并将它们与lastValueProperty()关联并将其绑定到closeingPrice属性。

我应该如何解决这个问题? (我想在这里保留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);

}


现在创建绑定:

this.closingPrice.bind(Bindings.createDoubleBinding(() ->
    priceService.getLastValue().getPrice(),
    priceService.lastValueProperty());
this.stockName.bind(Bindings.createStringBinding(() ->
    priceService.getLastValue().getName(),
    priceService.lastValueProperty());


(您可能需要处理priceService.getLastValue()null的情况。)

10-04 20:01