正如我们已经在这里讨论的,要设置每个条形的最大宽度,每次调整场景或图表大小时,我们都必须进行相应的更改barGap。categoryGap
与所提到的问题的唯一区别是我们必须在第一次显示时调整图表的大小。
基于相同的代码,让我们创建该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);
}
Run Code Online (Sandbox Code Playgroud)
现在创建图片的图表,但宽度为 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));
});
}
Run Code Online (Sandbox Code Playgroud)

编辑
setMaxBarWidth()我已将对with 的调用包装起来Platform.runLater(),因此场景图有时间正确刷新图表,避免在 while 循环期间进行多次重绘。另外,我已将侦听器移至bc.widthProperty(),以防图表嵌入到其他容器中。
| 归档时间: |
|
| 查看次数: |
4200 次 |
| 最近记录: |