0

I'm new in Java and I need a help. I want to add event to specific TreeItem in my TreeView. I have some code and it doesn't work. What am I doing wrong?

Here's my code:

TreeItem<String> item = new TreeItem<>(s);

item.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>(){
                public void handle(MouseEvent e) {
                    System.out.println("Hello World");
                }
            });

this.item.getChildren().add(item);

It creates a TreeView, but the event doesn't work.

Thanks for your help.

1 Answers1

2

I think you want to handle that if you click on a TreeItem this can ba solved simple if you add a listener to the selected item:

treeTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
    if(newValue != null && newValue != oldValue){
           System.out.println("Hello World");
    }
});

If you are not familiar with java8's lambdas here is the version with anonymous class:

table.getSelectionModel().selectedItemProperty().addListener(new 
ChangeListener<TreeItem<TestRow>>() {
        @Override public void changed(
                ObservableValue<? extends TreeItem<TestRow>> observable,
                TreeItem<TestRow> oldValue,
                TreeItem<TestRow> newValue) {
            if (newValue != null && newValue != oldValue) {
                System.out.println("Hello World");
            }
        }
});
Sunflame
  • 2,993
  • 4
  • 24
  • 48