条形图的限制宽度大小

Limit width size of Bar chart

我创建了条形图的简单示例,但我注意到条形的大小适合图表。我如何限制大小?敌人的例子我想限制宽度大小。

正如我们已经讨论过的 here,要在每个条上设置最大宽度,我们必须相应地更改 barGapcategoryGap,每次场景或图表调整大小。

与引用问题的唯一区别是我们必须在第一次显示时调整图表的大小。

基于相同的代码,让我们创建 setMaxBarWidth() 方法:

private final NumberAxis yAxis = new NumberAxis();
private final CategoryAxis xAxis = new CategoryAxis();
private final BarChart<String,Number> bc = new BarChart<>(xAxis,yAxis);

private void setMaxBarWidth(double maxBarWidth, double minCategoryGap){
    double barWidth=0;
    do{
        double catSpace = xAxis.getCategorySpacing();
        double avilableBarSpace = catSpace - (bc.getCategoryGap() + bc.getBarGap());
        barWidth = (avilableBarSpace / bc.getData().size()) - bc.getBarGap();
        if (barWidth >maxBarWidth){
            avilableBarSpace=(maxBarWidth + bc.getBarGap())* bc.getData().size();
            bc.setCategoryGap(catSpace-avilableBarSpace-bc.getBarGap());
        }
    } while(barWidth>maxBarWidth);

    do{
        double catSpace = xAxis.getCategorySpacing();
        double avilableBarSpace = catSpace - (minCategoryGap + bc.getBarGap());
        barWidth = Math.min(maxBarWidth, (avilableBarSpace / bc.getData().size()) - bc.getBarGap());
        avilableBarSpace=(barWidth + bc.getBarGap())* bc.getData().size();
        bc.setCategoryGap(catSpace-avilableBarSpace-bc.getBarGap());
    } while(barWidth < maxBarWidth && bc.getCategoryGap()>minCategoryGap);
}

现在创建你的图片的图表,但宽度为 40 像素:

@Override 
public void start(Stage stage) {
    bc.setTitle("1");
    xAxis.setLabel("Groups");       
    yAxis.setLabel("Value");

    XYChart.Series series1 = new XYChart.Series();
    series1.setName("Groups");       
    series1.getData().add(new XYChart.Data("kk", 1));

    Scene scene  = new Scene(bc,800,600);
    bc.getData().addAll(series1);
    stage.setScene(scene);
    stage.show();

    setMaxBarWidth(40, 10);
    bc.widthProperty().addListener((obs,b,b1)->{
        Platform.runLater(()->setMaxBarWidth(40, 10));
    });
}

编辑

我用 Platform.runLater() 包装了对 setMaxBarWidth() 的调用,因此场景图有时间正确刷新图表,避免在 while 循环期间多次重绘。此外,我已将侦听器移至 bc.widthProperty(),以防图表嵌入其他容器中。