SDS
SDS

Reputation: 457

JavaFx Custom Bar Chart Mouse Event not triggering

I have a JavaFx Custom Bar Chart with label displayed on FXCanvas for SWT RCP application. Thanks to answers posted for How to clear text added in a javafx barchart?

However, when I add Mouse event listener to Nodes of the Bar Chart, Mouse event is not getting detected

private void addMouseListener(XYChart.Series<String, Number> series) {
            for (XYChart.Data<String, Number> xyData : series.getData()) {
                if (xyData != null && xyData.getNode() != null) {
                    final Node node = xyData.getNode();
                    node.setOnMousePressed((MouseEvent event) -> {
                        System.out.println("you clicked " + xyData.toString());
                        
                }
            }
        }

Invoking addMouseListener inside createBarChart with below lines of code

    BarChartExt barChart = new BarChartExt<String, Number>(xAxis, yAxis);
    barChart.setTitle("Summary");
    
    Scene scene = new Scene(barChart, 300, 300);
    barChart.getData().add(series);
    addMouseListener(series)
    scene.getStylesheets().add("css/barchart.css");
    canvas.setScene(scene);

If I change the Custom BarChart to javafx.chart.BarChart class, events are recognised. Only for Custom BarChart mouse events are not firing.

Appreciate if any one could help me with this usecase. TIA

Upvotes: 0

Views: 782

Answers (1)

SDS
SDS

Reputation: 457

The Custom Bar Chart was creating Series Data with TextFlow. Below is the snippet

    @Override
    protected void seriesAdded(Series<X, Y> series, int seriesIndex) {

        super.seriesAdded(series, seriesIndex);

        for (int j = 0; j < series.getData().size(); j++) {

            Data<X, Y> item = series.getData().get(j);
            Text text = new Text(String.valueOf(item.getYValue()););
            text.setStyle("-fx-font-size: 10pt;");

            TextFlow textFlow = new TextFlow(text);
            textFlow.setTextAlignment(TextAlignment.CENTER);

            nodeMap.put(item.getNode(), textFlow);
            getPlotChildren().add(textFlow);

            textFlow.setOnMousePressed((MouseEvent event) -> {
                System.out.println("custom bar chart you clicked " + item);
            });
        }
    }

Since the series data node was overlayed by the TextFlow. I had to add the listener to TextFlow instead of Node. Below if the screenshot of the Custom Bar Chart.

enter image description here

Upvotes: 1

Related Questions