mynameisJEFF
mynameisJEFF

Reputation: 4239

Javafx: Automatic update of table cell using Thread

I have a Trade class which contains a property currentPrice, which downloads price data from a website using getPricedata() method. The Trade object will show up as a table row in TableView. Now, my task: is to

Below is the basic structure of my code. But I have no idea how to implement this ? Which package do I need ? Task ? Service ? ScheduledService ?

public class Trade{

     private DoubleProperty currentPrice;

     // need thread here
     public double getPricedata(){
             .......
     } 
}

Upvotes: 1

Views: 247

Answers (1)

James_D
James_D

Reputation: 209330

Use a ScheduledService<Number>, whose Task<Number>'s call() method retrieves and returns the value. Then you can either register an onSucceeded handler with the service, or just bind the Trade's currentPrice to service.lastValue(). Call setPeriod(..) on the service (once) to configure it to run every minute.

Since the currentPrice is being set from the service, you should only expose a ReadOnlyDoubleProperty from your Trade class (otherwise you might try to call currentPriceProperty().set(...) or setCurrentPrice(...), which would fail as it's bound).

I would do something like

public class Trade {

    private final ReadOnlyDoubleWrapper currentPrice ;

    private final ScheduledService<Number> priceService = new ScheduledService<Number>() {
        @Override
        public Task<Number> createTask() {
            return new Task<Number>() {
                @Override
                public Number call() {
                    return getPriceData();
                }
            };
        }
    };

    public Trade() {
        priceService.setPeriod(Duration.minutes(1));

        // in case of errors running service:
        priceService.setOnFailed(e -> priceService.getException().printStackTrace());

        currentPrice = new ReadOnlyDoubleWrapper(0);
        currentPrice.bind(priceService.lastValueProperty());
        startMonitoring();
    }

    public final void startMonitoring() {
        priceService.restart();
    }

    public final void stopMonitoring() {
        priceService.cancel();
    }

    public ReadOnlyDoubleProperty currentPriceProperty() {
       return currentPrice.getReadOnlyProperty();
    }

    public final double getCurrentPrice() {
        return currentPriceProperty().get();
    }

    private double getPriceData() {
        // do actual retrieval work here...
    }
}

(Code just typed in here without testing, but it should give you the idea.)

Upvotes: 2

Related Questions