问题描述
我想在每个图表上绘制一个系列,最后将所有系列一起绘制在一个图表上,但没有成功。我正在寻求帮助。该代码简单明了。这是我的代码:
-
主类;
public class TestChart extends Application { GenPlots genPlots =new GenPlots(); @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setonAction(event -> { genPlots.GenPlots("Hello"); }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root,200,250); primaryStage.setTitle("TestCharts"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
-
该类旨在生成序列和图表:
public class GenPlots { public GenPlots() {}; Axis xAxis = new NumberAxis(); Axis yAxis = new NumberAxis(); LineChart<Number,Number> lineChart = new LineChart<Number,Number> (xAxis,yAxis); LineChart<Number,Number> lineChartMulti = new LineChart<Number,Number>(xAxis,yAxis); String serName="*"; // generate the linecharts public void GenPlots (String hello) { lineChart.getData().clear(); lineChartMulti.getData().clear(); for (int j=1; j<4;j++) { XYChart.Series serSIF = new XYChart.Series(); serSIF=getSeries(); serName=String.valueOf(j); serSIF.setName("Only one "+serName); lineChart.getData().add(serSIF); displayChart(lineChart,serName); lineChartMulti.getData().add(serSIF); } displayChart(lineChartMulti,serName+"All Series"); } // end method // get the series with values - sample public XYChart.Series getSeries() { double x=0.0; double fx=0.0; XYChart.Series serL = new XYChart.Series(); for (int k=1; k<5;k++) { x=x+2; fx=x*x*j; serL.getData().add(new XYChart.Data(x,fx)); } return serL; } // plot the lineCharts public void displayChart( LineChart<Number,Number>lineChart,String chartTitle ) { Stage window = new Stage(); window.initModality(Modality.NONE); StackPane vb = new StackPane(); vb.setPadding(new Insets(20,20,20)); lineChart.setTitle(chartTitle); vb.getChildren().add(lineChart); Scene scene = new Scene(vb,500,600); window.setScene(scene); window.show(); } }
此外,所有系列的最后一个图均正确显示,但其他图(每个图表一个序列)失真或完全没有绘制。似乎每次生成线图时,该系列都会重置为null。我认为是由于该系列是可观察的,但我不知道如何解决此问题。请问您的贡献
解决方法
我找到了解决方案,对其他人可能有用:
将系列保存到ObservableList-
ObservableList