Fix spacing between different series in JavaFX lin

2020-02-14 10:28发布

问题:

I want the item spacing to appear more orderly with a constant spacing

How can I do this? I combed through the JavaFX CSS properties and modena css, and I didn't see anything relevant that seemed to work. I only find these properties:

.chart-legend {
   -fx-background-color: white
   -fx-background-insets: 0 0 -1 0, 0,1;
   -fx-background-radius: 4,4,3;
   -fx-padding: 6px;
}

回答1:

The legend of a Chart is an arbitrary node. It's default implementation is a specialized TilePane, that is its children are sized uniformly across the available width. For a different layout that default implementation can be replaced with a custom legend, f.i. a FlowPane (or HBox).

A quick approach is to subclass LineChart, override updateLegend and replace the default with a custom pane. The example below is dirty in that it relies on implementation details of the default implementation

The custom LineChart:

public static class MyLineChart<X, Y> extends LineChart<X, Y> {

    public MyLineChart(Axis<X> xAxis, Axis<Y> yAxis) {
        super(xAxis, yAxis);
    }

    private TilePane legendAlias;
    private FlowPane legendReplacement;

    @Override
    protected void updateLegend() {

        // let super do the setup
        super.updateLegend();
        Node legend = getLegend();
        if (legend instanceof TilePane) {
            legendAlias = (TilePane) legend;
            legendReplacement = new FlowPane(10, 10);
            setLegend(legendReplacement);
        }
        if (legendAlias != null && legendAlias.getChildren().size() > 0) {
            legendReplacement.getChildren().setAll(legendAlias.getChildren());
            legendAlias.getChildren().clear();
            setLegend(legendReplacement);
        }
    }

}


标签: java css javafx