如何在JavaFX中显示多个饼图?

时间:2017-02-01 17:49:54

标签: java javafx charts hashmap pie-chart

好的,所以我正在使用JavaFX,我希望在一个窗口中显示多个饼图。每个馅饼将代表大学一个学位的一个模块,将有2个切片,超过他们在该模块中的平均水平的学生数量和下面的数量。我正在使用两个哈希映射,一个用于存储模块名称和表现良好的学生数量,另一个用于那些没有。“/ p>

我的代码目前显示一个模块的一个饼图。我很接近,但我如何得到所有的馅饼?

我的代码:

public class PieChartSample extends Application {
static Map<String, Integer> studsabove = new HashMap<String, Integer>();
static Map<String, Integer> studsbelow = new HashMap<String, Integer>();

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("My First JavaFX App");

    ArrayList<PieChart> pielist = new ArrayList<PieChart>();
    for(Entry<String, Integer> mod: studsabove.entrySet()){
        for(Entry<String, Integer> mod2: studsbelow.entrySet()){
            PieChart pieChart = new PieChart();
            PieChart.Data above = new PieChart.Data(mod.getKey(), mod.getValue());
            PieChart.Data below = new PieChart.Data(mod2.getKey(), mod2.getValue());

            pieChart.getData().add(above);
            pieChart.getData().add(below);

            pielist.add(pieChart);
        }
    }


    for (PieChart pie: pielist){
        VBox vbox = new VBox(pie);
    }
    //TODO: figure this shit out
    Scene scene = new Scene(vbox, 400, 200);

    primaryStage.setScene(scene);
    primaryStage.setHeight(300);
    primaryStage.setWidth(1200);

    primaryStage.show();
}

public static void main(String[] args) {

    PieChartSample.studsabove.put("CE201", 23);
    PieChartSample.studsbelow.put("CE201", 67);

    PieChartSample.studsabove.put("CE222", 20);
    PieChartSample.studsbelow.put("CE222", 80);


    PieChartSample.studsabove.put("CE233", 6);
    PieChartSample.studsbelow.put("CE233", 94);

    PieChartSample.studsabove.put("CE244", 56);
    PieChartSample.studsbelow.put("CE244", 44); 
    Application.launch(args);
}

1 个答案:

答案 0 :(得分:0)

for (PieChart pie: pielist){
    VBox vbox = new VBox(pie);
}

你在饼图中为每个PieChart创建一个新的VBox,它只包含你正在迭代的单个PieChart。

不要在For-Loop中反复启动VBox,而是在循环之前完成并添加每个PieChart。 试试这个:

VBox vbox = new VBox();
for (PieChart pie: pielist){
    vbox.getChildren().add(pie);
}

我不完全确定,但也可以使用儿童系列发起一个VBox,这样你也可以试试这个:

VBox vbox = new VBox(pielist);