在javafx中向treeitems添加eventhandler

时间:2016-10-19 12:53:06

标签: javafx javafx-8

package helloworld;

import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class TreeViewSample extends Application {

    /*private final Node rootIcon = new ImageView(
        new Image(getClass().getResourceAsStream("folder_16.png"))
    );*/

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Tree View Sample");        

        TreeItem<String> rootItem = new TreeItem<String> ("Jobs");
        TreeItem<String> rootItem2 = new TreeItem<String> ("Test");
        TreeItem<String> rootItem3 = new TreeItem<String> ("Datalens Help");
        rootItem.setExpanded(true);
        for (int i = 1; i < 6; i++) {
            TreeItem<String> item = new TreeItem<String> ("Message" + i);            
            rootItem.getChildren().add(item);

        }    


        List<TreeItem<String>> items=new ArrayList<>();



        TreeView<String> tree = new TreeView<String> (rootItem);  



      //  TreeView<String> tree2 = new TreeView<String> (rootItem2);
        StackPane root = new StackPane();
        root.getChildren().add(tree);
        //+-root.getChildren().add(tree2);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
        rootItem.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED
                , new EventHandler<javafx.scene.input.MouseEvent>() {

            @Override
            public void handle(javafx.scene.input.MouseEvent mouseEvent) {
                // TODO Auto-generated method stub
            System.out.println("yolo");
            mouseEvent.consume();
            }
        });
    }
}

我希望通过点击各个树项来触发事件,尽管上面的代码不起作用。如果我将处理程序添加到整个树视图,则会触发该事件。任何帮助将不胜感激。

0 个答案:

没有答案