JavaFX 2.0 - How to change legend color of a LineChart dynamically?

后端 未结 4 1850
醉话见心
醉话见心 2021-01-18 09:00

I am trying to style my JavaFX linechart but I have some trouble with the legend.

I know how to change the legend color of a line chart in the css file:

4条回答
  •  [愿得一人]
    2021-01-18 09:20

    I ran into this issue as well. The issue seems to be that when data series are added to the chart, the legend isn't updated at the same time, so when you lookup components with that seriesN style class they don't exist yet. Came up with a work-around that detects when the legend items are created so that dynamic styling can be added to them.

    I added a ListChangeListener to the chart legend's "getChildrenUnmodifiable()" ObservableList, which in turn adds a ListChangeListener to each of the legend's children as they get added. From within this listener, we can tell when new items are being added to the legend (or removed). This allow us to then make the dynamic style changes.

    for (Node n : lineChart.getChildrenUnmodifiable())
        {
            if (n instanceof Legend)
            {
                final Legend legend = (Legend) n;
    
                // remove the legend
                legend.getChildrenUnmodifiable().addListener(new ListChangeListener()
                {
                    @Override
                    public void onChanged(Change arg0)
                    {
                        for (Node node : legend.getChildrenUnmodifiable())
                        {
                            if (node instanceof Label)
                            {
                                final Label label = (Label) node;
                                label.getChildrenUnmodifiable().addListener(new ListChangeListener()
                                {
                                    @Override
                                    public void onChanged(Change arg0)
                                    {
                                        //make style changes here
                                    }
    
                                });
                            }
                        }
                    }
                });
            }
        }
    
        

    提交回复
    热议问题