JavaFX Use Chart Legend to toggle show/hide Series possible?

Viewed 6037

Is it possible to use a chart's legend to toggle show/hide a series?

I got a LineChart with a legend and there are too many Series so you can't read out the information well. I was wondering if there is a possibility to use the legend to toggle the series to show/hide?

Most of the names of my Series are pretty long and it looks very weird if they are written twice once in the legend so you know which color belongs to which Series and a second time besides a CheckBox to toggle them.

Edit1: Maybe I was unclear, even if there is no built in function for this, I could use some input for how a workaround could look like, because I can't come up with anything.

5 Answers

A bit off-topic, but too long for a comment and useful if you've made the switch to TornadoFX (which is based on JavaFX). Hiding the series can be achieved behind the scenes by adding the extension

fun XYChart<Number, Number>.showExtra(on: Boolean) {

    for (s in getData()) {

        s.getNode().setVisible(on)

        for (d in s.getData()) {

            if (d.getNode() != null) {

                d.getNode().setVisible(on)
            }
        }
    }
}

This code works with new versions of JavaFX and with Kotlin. It also solves the problem of import com.sun.javafx.charts package:

val items: Set<Node> = lineChart.lookupAll("Label.chart-legend-item")
    items.forEach { label ->
        if(label is Label)
            label.setOnMouseClicked {
                lineChart.data.forEach {
                    if(it.name == label.text) {
                        it.node.isVisible = !it.node.isVisible
                    }
                }
            }
    }
Related