gpt4 book ai didi

java - 如何在条形图 javafx 顶部显示条形图值

转载 作者:行者123 更新时间:2023-11-28 01:15:19 24 4
gpt4 key购买 nike

从这段代码我可以生成 10 个条形图现在我想知道如何在条形图的顶部显示每个条形图的值,如附图:enter image description here

代码如下:

public class BarChartSample extends Application {


@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<String,Number>(xAxis,yAxis);
bc.setTitle("Country Summary");
xAxis.setLabel("bars");
yAxis.setLabel("Value");

XYChart.Series series1 = new XYChart.Series();
series1.setName("...");

for(int i=0;i<10;i++)
{
//here i want to change color of bar if value of i is >5 than red if i>8 than blue
series1.getData().add(new XYChart.Data("Value", i));

}

}

public static void main(String[] args) {
launch(args);
}
}

最佳答案

在每个数据项的 node 属性的 ChangeListener 中,您可以调用以下函数将标签添加到栏的顶部:

private void displayLabelForData(XYChart.Data<String, Number> data) {
final Node node = data.getNode();
final Text dataText = new Text(data.getYValue() + "");
node.parentProperty().addListener(new ChangeListener<Parent>() {
@Override public void changed(ObservableValue<? extends Parent> ov, Parent oldParent, Parent parent) {
Group parentGroup = (Group) parent;
parentGroup.getChildren().add(dataText);
}
});

node.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
@Override public void changed(ObservableValue<? extends Bounds> ov, Bounds oldBounds, Bounds bounds) {
dataText.setLayoutX(
Math.round(
bounds.getMinX() + bounds.getWidth() / 2 - dataText.prefWidth(-1) / 2
)
);
dataText.setLayoutY(
Math.round(
bounds.getMinY() - dataText.prefHeight(-1) * 0.5
)
);
}
});
}

代码的工作原理是向每个条形节点的父节点添加一个文本标签,然后在每次调整条形大小时基于条形和文本边界动态定位文本标签。

我创建了一个 sample solution为此。

labeledchartwithlegend

关于java - 如何在条形图 javafx 顶部显示条形图值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com