StockComponent.java
package edu.ntnu.idi.idatt.view.components.elements;
import java.util.List;
import java.util.function.Consumer;
import edu.ntnu.idi.idatt.model.market.Stock;
import edu.ntnu.idi.idatt.view.components.ui.UICompositor;
import edu.ntnu.idi.idatt.view.util.CssUtils;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* Stock Component class.
*
* <p>
* JavaFX Component for handeling repetative tasks.
* Creates a visual representation of a standalone Stock given.
* </p>
*
* @see Stock
*/
public class StockComponent extends HBox {
private final Stock stock;
/**
* Constructor for StockComponent
*
* @param stock - Stock component to create the component for.
*/
public StockComponent(Stock stock) {
this.stock = stock;
this.setMaxSize(Double.MAX_VALUE, 100);
this.setPadding(new Insets(40));
this.setAlignment(Pos.BASELINE_CENTER);
this.setStyle("-fx-background-color: #404950;");
Label title = new Label(stock.toString());
Label latestText = new Label("Latest");
Label latestValue = new Label(String.format("%.2f USD", stock.getSalesPrice()));
Label changeText = new Label("Change");
Label changeValue = new Label(String.format("%.2f USD", stock.getLatestPriceChange()));
Label changeValuePercent = new Label(
String.valueOf(stock.getLatestPriceChangePercent()) + "%");
List<Label> labels = List.of(latestText, latestValue, changeText, changeValue, changeValuePercent);
CssUtils.apply(title, CssUtils.BIG_TEXT_32);
labels.forEach(l -> CssUtils.apply(l, CssUtils.MED_TEXT_16));
String color = CssUtils.generateValueColors(stock.getLatestPriceChange());
CssUtils.apply(changeValue, color);
CssUtils.apply(changeValuePercent, color);
UICompositor stockComponent = new UICompositor.Builder()
.parent(new HBox())
.growWithAlignment(Pos.CENTER)
.addContent(title)
.filler()
.filler()
.filler()
.wrap(new VBox())
.addAllContent(latestText, latestValue)
.unwrap()
.filler()
.wrap(new VBox())
.addAllContent(changeText, changeValue, changeValuePercent)
.unwrap()
.build();
// Add click cursor
this.setCursor(Cursor.HAND);
this.getChildren().addAll(stockComponent.makeUI());
}
/**
* Method for handeling component click.
*
* @param handler - Functional interface with reference to the stock symbol.
*/
public void onStockClick(Consumer<String> handler) {
this.setOnMouseClicked((e) -> handler.accept(stock.getSymbol()));
}
}