将值标签添加到BarChart的栏中

时间:2013-01-02 17:22:15

标签: javafx-2 bar-chart

我想在BarChart

的每个条形图的顶部或正文上添加条形数值的标签

我在API和CSS参考指南中都进行了搜索,但找不到任何定义它的选项。

当前版本的JavaFX图表是否支持此功能?

2 个答案:

答案 0 :(得分:2)

这个怎么样:

import javafx.scene.chart.Axis;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.StackedBarChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;

class CustomStackedBarChart extends StackedBarChart<String, Number> {

    public CustomStackedBarChart(CategoryAxis xAxis, Axis<Number> yAxis) {
        super(xAxis, yAxis);
    }

    @Override
    protected void layoutPlotChildren() {
        super.layoutPlotChildren();

        for (Series<String, Number> series : getData()) {
            for (Data<String, Number> data : series.getData()) {
                StackPane bar = (StackPane) data.getNode();

                final Text dataText = new Text(data.getYValue() + "");
                bar.getChildren().add(dataText);

            }
        }
    }
}

答案 1 :(得分:1)

我正在尝试做同样的事情。到目前为止,这就是我所拥有的。

class CustomStackedBarChart extends StackedBarChart<String, Number> {

    public CustomStackedBarChart( CategoryAxis xAxis, Axis<Number> yAxis ) {
        super( xAxis, yAxis );

        setAnimated( false );
        setLegendVisible( false );
        setTitleSide( Side.TOP );
        setTitle( "SSPP Diurnal Symbol Rate" );
        setMinHeight( 500 );
        setMinWidth( 1000 );
    }

    @Override
    protected void layoutPlotChildren() {
        super.layoutPlotChildren();

        // Each individual Data element has its own bar.
        // TODO add label to each bar.
        for ( Series<String, Number> series : getData() ) {
            for ( Data<String, Number> data : series.getData() ) {
                StackPane bar = (StackPane) data.getNode();

                Label label = null;

                for ( Node node : bar.getChildrenUnmodifiable() ) {
                    LOGGER.debug( "Bar has child {}, {}.", node,
                        node.getClass() );
                    if ( node instanceof Label ) {
                        label = (Label) node;
                        break;
                    }
                }

                if ( label == null ) {
                    label = new Label( series.getName() );
                    label.setRotate( 90.0 );
                    bar.getChildren().add( label );
                }
                else {
                    label.setText( series.getName() );
                }
            }
        }
    }
}