在 JavaFX 8 中,当 xAxis 虽然定义为字符串但表示数字时,我如何对 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 文件生成了条形图。下面是我使用的代码片段:

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); 

请帮忙,提前致谢!

请您参考如下方法:

您需要对类别进行排序。

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); 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!