This is the code for interface:
@Override
public void start(Stage primaryStage){
NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("XX");
NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("YY");
LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setLegendVisible(false);
XYChart.Series<Number, Number> series1 = new XYChart.Series<>();
series1.setName("Line1");
series1.getData().add(new XYChart.Data<>(1, 1));
series1.getData().add(new XYChart.Data<>(2, 2));
series1.getData().add(new XYChart.Data<>(3, 2));
series1.getData().add(new XYChart.Data<>(4, 1));
XYChart.Series<Number, Number> series2 = new XYChart.Series<>();
series2.setName("Line2");
series2.getData().add(new XYChart.Data<>(2, 2));
series2.getData().add(new XYChart.Data<>(3, 2));
series2.getData().add(new XYChart.Data<>(4, 2));
XYChart.Series<Number, Number> series3 = new XYChart.Series<>();
series3.setName("Line3");
series3.getData().add(new XYChart.Data<>(1, 3));
series3.getData().add(new XYChart.Data<>(2, 2));
series3.getData().add(new XYChart.Data<>(3, 1));
series3.getData().add(new XYChart.Data<>(3, 2));
List<XYChart.Series<Number, Number>> seriesList = Arrays.asList(series1, series2, series3);
lineChart.getData().addAll(seriesList);
HBox legendBox = new HBox();
legendBox.setStyle("-fx-alignment: center; -fx-padding: 10;");
Insets insets = new Insets(0, 10, 0, 10);
for(Node legend : lineChart.lookupAll(".chart-legend-item")){
Label label = (Label)legend;
label.setOnMouseClicked(e -> {
XYChart.Series<Number, Number> toFront = seriesList.stream()
.filter(e1 -> e1.getName().equals(label.getText()))
.findFirst().get();
System.out.println(toFront);
//put series toFront over all other series
//i don't know how//
/*I have tried this
Platform.runLater(() -> {
lineChart.getData().remove(toFront);
lineChart.getData().add(toFront); //first time click: Duplicate, after only NullPointer
});*/
});
legendBox.getChildren().add(label);
HBox.setMargin(label, insets);
}
BorderPane borderPane = new BorderPane();
borderPane.setCenter(lineChart);
borderPane.setBottom(legendBox);
primaryStage.setScene(new Scene(borderPane));
primaryStage.sizeToScene();
primaryStage.centerOnScreen();
primaryStage.show();
}
This is how interface looks:
As you can see in image, you can't know the exact path of Line1
and Line2
.
I want to put an EventHandler
on legends. When you click on one of the legends, place the line of legend in front of chart, over all others lines.
The code with EventHandler
, as you can see, is writen. After the series is identified I don't know what do to. I have tried to remove from chart and add again:
Platform.runLater(() -> {
lineChart.getData().remove(toFront);
lineChart.getData().add(toFront);
});
Which only remove line and result errors:
1. First click: "Duplicate series added" //at line with add
2. Next clicks: "NullPointerException" //at line with add