我有一个问题,当我将数据添加到类别轴并且之前使用过轴标题时,顺序被搞砸了。运行下面的简单应用程序并在图表上单击两次并查看 x 轴以了解我的意思。数据从第 0 个月到第 10 个月提供给图表,但以另一种顺序显示。有什么帮助吗?
package testCategoryBug;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.input.MouseEvent;
public class TestCategoryBug extends Application {
static Boolean even=true;
@Override public void start(Stage stage) {
stage.setTitle("Test Category Bug");
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Month");
final LineChart<String,Number> lineChart = new LineChart<String,Number>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
// Initialize some data for plotting.
final Series<String, Number> plottablePairs = new Series<String, Number>();
final Series<String, Number> plottablePairs2 = new Series<String, Number>();
for (int i = 0; i < 10; i++) {
Data<String,Number> pair= new Data<String,Number>("Month "+i,10.0*i);
plottablePairs.getData().add(pair);
}
for (int i = 5; i < 10; i++) {
Data<String,Number> pair= new Data<String,Number>("Month "+i,100.0-10*i);
plottablePairs2.getData().add(pair);
}
// add the first of the series
final ObservableList<XYChart.Series<String, Number>> chartData=FXCollections.observableArrayList();;
chartData.add(plottablePairs);
lineChart.setData(chartData);
// now on a mouse click, swap the data. Click twice and see what happens
lineChart.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
chartData.clear();
if (even) {
chartData.add(plottablePairs2);
} else {
chartData.add(plottablePairs);
// note that after this, the axis is screwed up.
}
lineChart.setData(chartData);
even=!even;
}
});
// Put up the scene
Scene scene = new Scene(lineChart,800,600);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}