当定义为字符串的xAxis表示数字时,如何对JavaFX 8中的BarChart的xAxis进行排序或排序?例如:
@Override public void start(Stage stage) {
stage.setTitle("Bar Chart Sample");
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final BarChart<String,Number> bc =
new BarChart<>(xAxis,yAxis);
bc.setTitle("Country Summary");
xAxis.setLabel("Number");
yAxis.setLabel("Value");
XYChart.Series series1 = new XYChart.Series();
series1.setName("Series-1");
series1.getData().add(new XYChart.Data("2",200));
series1.getData().add(new XYChart.Data("3",500));
series1.getData().add(new XYChart.Data("4",100));
XYChart.Series series2 = new XYChart.Series();
series2.setName("Series-2");
series2.getData().add(new XYChart.Data("1",900));
series2.getData().add(new XYChart.Data("2",150));
series2.getData().add(new XYChart.Data("3",50));
series2.getData().add(new XYChart.Data("4",700));
Scene scene = new Scene(bc,800,600);
bc.getData().addAll(series1, series2);
stage.setScene(scene);
stage.show();
}虽然这是显示问题的一种简单方式,但在我的代码中,我是从一个巨大的excel文件生成BarChart。我使用的代码片段如下:
final ObservableList<XYChart.Series<String,Number>> barChartData = FXCollections.observableArrayList();
Iterator<Map.Entry<String, ArrayList<XYBean>>> it = xyBean.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, ArrayList<XYBean>> entry = it.next();
XYChart.Series series = new XYChart.Series<>();
series.setName(entry.getKey());
for (XYBean xybean : entry.getValue()) {
series.getData().add(new XYChart.Data(xybean.getxValue(), xybean.getyValue()));
}
barChartData.add(series);
}
barChart.setData(barChartData);请帮助,并提前感谢!
发布于 2017-06-10 16:39:30
您需要对类别进行排序。
Collections.sort(xAxis.getCategories());然而,不能在上工作。
的一种工作方式如下所示:
// fill this whenever you add new data to the chart
private final Set<String> categories = new LinkedHashSet<>();
// after all data is added to the chart, sort the categories, set them manually and enable auto-ranging again (if needed)
final ObservableList<String> c = FXCollections.observableArrayList(categories);
Collections.sort(c);
xAxis.setCategories(c);
xAxis.setAutoRanging(true);发布于 2015-05-09 01:26:29
一种方法是从xAxis获取类别,并使用比较器对它们进行排序。尽管我的印象是Category Axis无论如何都是自己做这件事的。
ObservableList<String>list = xAxis.getCategories();
Comparator<String> byValue = (e1, e2) -> Integer.compare(Integer.parseInt(e1), Integer.parseInt(e2));
xAxis.setCategories(list.sort(byValue));https://stackoverflow.com/questions/30128975
复制相似问题