如何在javafx栏上显示条形值

从这个代码我可以生成10条形的条形图现在我想知道如何在条形图上显示每个条形的值,如附加图像: 在此处输入图像描述

这是代码:

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 bc = new BarChart(xAxis,yAxis); bc.setTitle("Country Summary"); xAxis.setLabel("bars"); yAxis.setLabel("Value"); XYChart.Series series1 = new XYChart.Series(); series1.setName("..."); for(int i=0;i5 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 data) { final Node node = data.getNode(); final Text dataText = new Text(data.getYValue() + ""); node.parentProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Parent oldParent, Parent parent) { Group parentGroup = (Group) parent; parentGroup.getChildren().add(dataText); } }); node.boundsInParentProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue 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 ) ); } }); } 

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

我为此创建了一个示例解决方案 。

labeledchartwithlegend

JFX中没有关于条形图中条形图标签的选项。

您可以做的是扩展条形图类,并覆盖有关内容创建和分配的方法。

您可以在javafx-ui-charts项目中观察图表代码,您可以从OpenJFX存储库下载该代码。

图表代码不难理解……

从http://hg.openjdk.java.net/openjfx/8/master/rt下载rt-repository

找到项目javafx-ui-charts并打开它。 查找条形图的实现。