如何在javafx栏上显示条形值 [英] how to display bar value on top of bar javafx
本文介绍了如何在javafx栏上显示条形值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从这段代码我可以生成10个条形的条形图现在我想知道如何在条形图上显示每个条形图的值,如附加图像:
from this code i can generate bar chart of 10 bars now i want to know how to display value of each bar on top of bar like the attached image:
这里是代码:
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);
}
}
推荐答案
里面对于每个数据项的节点
属性, ChangeListener
,您可以调用以下函数将标签添加到顶部栏:
Inside a ChangeListener
for the each data item's node
property, you can call the following function to add a label to the top of the bar:
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
)
);
}
});
}
代码的工作原理是向每个条形节点的父节点添加文本标签,然后在每次调整条形大小时根据条形和文本的边界动态定位文本标签。
The code works by adding a text label to the parent of each bar node, then dynamically positioning the text label based on the bar and text's bounds each time the bar is resized.
我创建了一个示例解决方案。
这篇关于如何在javafx栏上显示条形值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文