2

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

测试应用程序.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 的图形,或者我是否以错误的方式考虑这一点?

4

0 回答 0