How do I specify the axis type for the chart from the FXML file? It seems like the default types are <String, Integer>
. If I declare my injectable field as LineChart<Number, Number> lineChart
, and the I create a data series with (Number, Number
), the program throws a ClassCastException
.
It is mandatory for a FXML File to be used. The worst case scenario would be that I created my chart manually. My best guess is that this is a bug.
import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.chart.LineChart; import javafx.scene.chart.XYChart; import javafx.scene.layout.AnchorPane; /** * * @author ggrec * */ public class TestChart implements Initializable { // ====================== 2. Instance Fields ============================= @FXML private LineChart<Number, Number> testChart; private AnchorPane anchorPane; // ==================== 4. Constructors ==================== public TestChart() { final FXMLLoader fxmlLoader = new FXMLLoader( TestChart.class.getResource("testChart.fxml") ); fxmlLoader.setController(this); try { anchorPane = (AnchorPane) fxmlLoader.load(); } catch (final IOException e) { e.printStackTrace(); } } // ==================== 5. Creators ==================== @Override public void initialize(final URL arg0, final ResourceBundle arg1) { // testChart.getXAxis().setAutoRanging(true); // testChart.getYAxis().setAutoRanging(true); testChart.getData().add(getDummyData()); } // ==================== 7. Getters & Setters ==================== public AnchorPane getAnchorPane() { return anchorPane; } // ==================== 13. Utility Methods ==================== private XYChart.Series getDummyData() { final XYChart.Series series = new XYChart.Series(); series.setName("My portfolio"); series.getData().add(new XYChart.Data<Number, Number>(1, 23)); // Works for ("1", 23) // series.getData().add(new XYChart.Data("2", 14)); // series.getData().add(new XYChart.Data("3", 15)); // series.getData().add(new XYChart.Data("4", 24)); // series.getData().add(new XYChart.Data("5", 34)); // series.getData().add(new XYChart.Data("6", 36)); // series.getData().add(new XYChart.Data("7", 22)); // series.getData().add(new XYChart.Data("8", 45)); // series.getData().add(new XYChart.Data("9", 43)); // series.getData().add(new XYChart.Data("10", 17)); // series.getData().add(new XYChart.Data("11", 29)); // series.getData().add(new XYChart.Data("12", 25)); return series; } }
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at javafx.scene.chart.CategoryAxis.invalidateRange(CategoryAxis.java:399) at javafx.scene.chart.XYChart.updateAxisRange(XYChart.java:603) at javafx.scene.chart.XYChart.layoutChartChildren(XYChart.java:620) at javafx.scene.chart.Chart$1.layoutChildren(Chart.java:84) at javafx.scene.Parent.layout(Parent.java:1018)