Remove JavaFX 2 LineChart Legend Items

Related searches

I have a line chart with many series. These series are grouped into one or more super-series. Each super-series may have many "breaks" in the line in order to accurately depict when a monitor process is not actively collecting data. Each data break is actually starting a new series.

I have been able to successfully overcome several technical issues with this such as the chart assigning a new color to each new series, chart line symbol color not matching the series color, etc. All is working quite well right now, except that each time I add a new series to the chart, it adds an item to the legend.

Is there a way to remove items from the legend, or do I have to hide the default legend and add my own custom legend pane?

Don't show the legend:

chart.setLegendVisible(false);

You can then create your own custom pane to make your own legend and render it how you wish.

How to remove legends in javafx line chart, Since you are already dealing with Legend , you can work with its items, removing those you don't need, so the legend shows only two items. Using streams, you� JavaFX LineChart legend style. 2. JavaFx BarChart Legend Color. 576. Ways to iterate over a list in Java. 7. Remove JavaFX 2 LineChart Legend Items. 0. Javafx HBox

After several failed attempts at implementing various suggestions, I found that the best way to allow a user to show/hide a data series in a JavaFx Chart (or sub-classes thereof) is to extend the chart class you want to use and override its updateLegend() method.

It's quite simple actually. Here's an example using a basic HBox as the legend containing check boxes as the legend items. In this example I have decided to make my LineChart with fixed axes types (CategoryAxis and NumberAxis). You might choose to leave your sub-class with generics for axes.

public class AtopLineChart<X, Y> extends LineChart<String, Number>
{

   /**
    * @param xAxis
    * @param yAxis
    */
   public AtopLineChart(final CategoryAxis xAxis, final NumberAxis yAxis)
   {
      super(xAxis, yAxis);
   }

   /* (non-Javadoc)
    * @see javafx.scene.chart.LineChart#updateLegend()
    */
   @Override
   protected void updateLegend()
   {
      final HBox legend = new HBox();
      legend.setVisible(true);
      for (final javafx.scene.chart.XYChart.Series<String, Number> series : getData())
      {
         final CheckBox cb = new CheckBox(series.getName());
         cb.setUserData(series);
         cb.setSelected(true);
         cb.addEventHandler(ActionEvent.ACTION, e ->
         {
            final CheckBox box = (CheckBox) e.getSource();
            @SuppressWarnings("unchecked")
            final Series<String, Number> s = (Series<String, Number>) box.getUserData();
            s.getNode().setVisible(box.isSelected());
         });
         legend.getChildren().add(cb);
      }
      setLegend(legend);
   }
}

I'll leave it as an exercise for the reader to make the legend more readable, for example, borders around each checkbox and binding the color of the series to the something showing that color in the checkbox for the series.

One other thing, you might want to check the getLegendSide() method to decide which kind of layout container to use for the legend, i.e. HBox for TOP and BOTTOM but VBOX for LEFT and RIGHT. Your choice.

JavaFX Use Chart Legend to toggle show/hide Series possible , LineChart<Number, Number> chart; for (Node n : chart. I match the legend item to the correct series based on the name - from my experience (int i = 0; i < 3; i ++) { XYSeries series = new XYSeries("value" + i); for (double t = 0; t < 2 * Math. javafx.scene.chart.LineChart<X,Y> This is called whenever a series is added or removed and the legend needs to be updated to remove the items node from being

You can find a node based on it's type (and optionally style name) using this method:

private static Node findNode(final Parent aParent, final String aClassname, final String aStyleName) {

    if (null != aParent) {
        final ObservableList<Node> children = aParent.getChildrenUnmodifiable();
        if (null != children) {
            for (final Node child : children) {

                String className = child.getClass().getName();

                if (className.contains("$")) {
                    className = className.substring(0, className.indexOf("$"));
                }

                if (0 == aClassname.compareToIgnoreCase(className)) {
                    if ((null == aStyleName) || (0 == aStyleName.length())) {
                        // No aStyleName, just return this:
                        return child;
                    }
                    else {
                        final String styleName = child.getStyleClass().toString();
                        if (0 == aStyleName.compareToIgnoreCase(styleName)) {
                            return child;
                        }
                    }
                }

                if (child instanceof Parent) {
                    final Node node = findNode((Parent) child, aClassname, aStyleName);

                    if (null != node) {
                        return node;
                    }
                }
            }
        }
    }

    return null;
}

Calling it with the chart in question to retrieve the Legend node:

Legend legend = (Legend) findNode(chart, Legend.class.getName(), "chart-legend");

Which you can then iterate through the children and remove the ones you don't want to be displayed:

    for (final Node legendItem : legend.getChildren()) {

        final Label legendLabel = (Label) legendItem;

        if (0 == legendLabel.getText().compareToIgnoreCase("the name of the legend I want hidden (or replaced with some other test)")) {
            legend.getChildren().remove(legendItem);
            break;
        }
    }

JavaFX also has a lookup function which "Finds this Node, or the first sub-node, based on the given CSS selector." and acts similar to the findNode function from this answer.

Using JavaFX Charts: Styling Charts with CSS, All visual elements of JavaFX charts are defined by the caspian style sheet. The chart legend for the line chart shown in Figure 8-3 has the default look and feel. Disable the color set for the tick labels in Example 5-5 by either deleting or � Remove JavaFX 2 LineChart Legend Items. 1. JAVAFX LineChart Hide/Show lines. Hot Network Questions If rocket engines only need fuel and oxidizer, then why there are

From a similar case, https://stackoverflow.com/a/27819227/2341336

This solution takes advantage of streams in Java and directly modifies the Legend object.

However, this is deprecated so it is not recommended.

Since you are already dealing with Legend, you can work with its items, removing those you don't need, so the legend shows only two items.

Using streams, you can mark the first two items as "Valid"/"Invalid" and the rest as "Remove", for instance, and finally you just remove these last items.

private void updateStyleSheet() {
    Legend legend = (Legend)lineChart.lookup(".chart-legend");
    AtomicInteger count = new AtomicInteger();
    legend.getItems().forEach(item->{
        if(count.get()==0){
            item.setText("Valid");
        } else if(count.get()==1){
            item.setText("Invalid");
        } else {
            item.setText("Remove");
        }
        count.getAndIncrement();
    });
    legend.getItems().removeIf(item->item.getText().equals("Remove"));

    ...
}

Using JavaFX Charts: Line Chart, If you want to show trends instead of specific data values on your line chart, you can disable the chart symbols as shown in Example 3-2. Example 3-2 Disabling� JavaFX StackedBarChart legend color don't follow chart color CSS styled. JavaFX 2.0 - How to change legend color of a LineChart dynamically? JavaFX LineChart legend style. EDIT: THIS IS THE SOLUTION I FOUND. None of this worked for me so, I found another solution. Neither the answer nor the Platform.runLater method.

Remove JavaFX 2 LineChart Legend Items, Remove JavaFX 2 LineChart Legend Items. 霸刀☆藐视天下 关注. 发布时间:2019- 02-22 07:06. I have a line chart with many series. These series are grouped� javafx.scene.chart.LineChart<X,Y> This is called whenever a series is added or removed and the legend needs to be updated to remove the items node from being

The line chart shown in Figure 3-2 uses symbols to highlight each data item on the chart. If you want to show trends instead of specific data values on your line chart, you can disable the chart symbols as shown in Example 3-2 .

8 Styling Charts with CSS. This chapter explains how to change the default appearance of JavaFX charts by applying Cascading Style Sheets (CSS). Learn how to change a chart color scheme, modify its legend or axes, and alter chart symbols.

Comments
  • Thanks! That's what I was afraid of. :)
  • Hey @jewelsea, One more question, if you don't mind. I've created my own custom pane to display my custom legend. It looks almost exactly like the original. The only thing I am having trouble with is making it shrink its width when there are just a couple of series. The chart and legend are in a VBox on a dialog, and the legend is on a StackPane in the bottom section of the VBox. The height changes appropriately. Do you have any more words of wisdom that can help me out?
  • Yep, but ask a new question and include your current code as an sscce in it.
  • Thanks again. I was able to overcome my challenge using the setPrefColumns() method on my legend, which is an instance of TilePane.
  • You can alter the standard legend, see below for example code.
  • getChildren() method is not visible to Legend class. Method getchildren() is protected in Parent class and extended by Region and so to Legend class. More over we can not remove elements from legend.getChildrenUnmodifiable()
  • @Kishore Running against Java 8.0.25, Legend's class hierarchy is: Object --> Node --> Parent --> Region --> Pane --> TilePane --> Legend. Pane has a public getChildren.
  • @Kishore seems like this was the change that made it possible: hg.openjdk.java.net/openjfx/8u-dev/rt/rev/9823085ebf0e