Steve
Steve

Reputation: 1051

JavaFX add Mouse Listener to TreeCell Graphic

I'm trying to add a MouseClicked event listener to a Tree Cell so that It fires when a user clicks on either the Graphic or the String value of the cell.

TestApp.java

public class TestApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Image image = new Image(getClass().getResourceAsStream("icon.png"));

        TreeItem<String> root = new TreeItem<String>("Root");
        root.setGraphic(new ImageView(image));

        TreeItem<String> child = new TreeItem<String>("Child");
        root.getChildren().add(child);

        TreeView<String> tree = new TreeView<String>(root);
        tree.setCellFactory(new TestTreeCellFactory());

        StackPane pane = new StackPane();
        pane.getChildren().add(tree);
        stage.setScene(new Scene(pane, 300, 250));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private class TestTreeCellFactory implements Callback<TreeView<String>, TreeCell<String>> {
        @Override
        public TreeCell<String> call(TreeView<String> treeView) {
            CheckBoxTreeCell<String> tc = new CheckBoxTreeCell<String>();
            tc.setOnMouseClicked((event) -> mousePressed(event, treeView));
            return tc;
        }

        public void mousePressed(MouseEvent event, TreeView<String> treeView) {
            if(event.getButton().equals(MouseButton.SECONDARY)) {
                System.out.println("Right Mouse Button Clicked!");
            }
        }
    }
}

The mouse event is currently firing when I click on the String Value but is not firing when I click on the Graphic icon. Upon trying to debug the issue, here are some of my observations:

Is there a way to attach the listener to the Tree Cell's graphic once it gets populated or am I thinking about this in the wrong way?

Upvotes: 2

Views: 739

Answers (0)

Related Questions