2

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:

  • It seems like the Graphic is somehow tied to the Checkbox (clicking on the Graphic will toggle the checkbox value).
  • Clicking the Graphic will not select the row while clicking on the text value will.

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?

Steve
  • 981
  • 1
  • 8
  • 22
  • Here is a useful tutorial on Oracle's site: http://docs.oracle.com/javafx/2/ui_controls/tree-view.htm – Jedi_Maseter_Sam Mar 21 '16 at 20:49
  • 1
    I've read this tutorial already and it didn't seem to address my problem. It even states that a TreeCell is a representation of a TreeItem, so you would think that putting a listener on the Cell would affect the entire Item, but that doesn't seem to be the case. – Steve Mar 22 '16 at 12:21

0 Answers0