I have an FXML file chart.fxml
and a Controller class Controller.java
for that FXML file. I wanted to make a LineChart using SceneBuilder, and initialize its data using a Controller.
However, when I run my program, the LineChart has no data/just shows the default LineChart.
This is my Controller.java
class:
package exercise;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import java.util.HashMap;
import java.util.Map;
public class Controller {
@FXML
private LineChart<Number, Number> lineChart;
void initData() {
Map<Integer, Integer> map = initMap();
NumberAxis x = new NumberAxis(
map.entrySet().stream()
.min((p1, p2) -> p2.getKey() - p1.getKey())
.get()
.getKey(),
map.entrySet().stream()
.min((p1, p2) -> p2.getKey() - p1.getKey())
.get()
.getValue(), 4
);
NumberAxis y = new NumberAxis();
x.setLabel("Year");
y.setLabel("Ranking");
this.lineChart = new LineChart<>(x, y);
this.lineChart.setTitle("Chart");
XYChart.Series data = new XYChart.Series();
data.setName("Ranks");
map.forEach((key, value) -> data.getData().add(new XYChart.Data(key, value)));
lineChart.getData().add(data);
}
private HashMap<Integer, Integer> initMap() {
HashMap<Integer, Integer> values = new HashMap<>();
values.put(2007, 73);
values.put(2008, 68);
values.put(2009, 72);
values.put(2010, 72);
values.put(2011, 74);
values.put(2012, 73);
values.put(2013, 76);
values.put(2014, 73);
values.put(2015, 67);
values.put(2016, 56);
values.put(2017, 56);
return values;
}
}
This is my Main
class:
package exercise;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
@Override
public void start(Stage window) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/chart.fxml"));
window.setScene(new Scene(loader.load()));
Controller controller = loader.getController();
controller.initData();
window.show();
}
public static void main(String[] args) {
launch(args);
}
}
How do I fix this?