JavaFX将鼠标侦听器添加到TreeCell图形

时间:2016-03-21 18:43:00

标签: java javafx treeview mouselistener treecell

我尝试将一个MouseClicked事件监听器添加到Tree Cell,以便在用户单击该单元格的Graphic或String值时触发它。

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!");
            }
        }
    }
}

单击“字符串值”时,鼠标事件当前正在触发,但单击“图形”图标时未触发。在尝试调试问题时,我的一些观察结果如下:

  • 似乎图形以某种方式绑定到复选框(单击图形将切换复选框值)。
  • 单击图形将不会选择该行,而单击文本值将为。

有没有办法在侦听器填充后将其附加到Tree Cell的图形中,或者我是否以错误的方式思考这个问题?

0 个答案:

没有答案