Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8116274

Method isSelected() in TreeCell always returns false

XMLWordPrintable

      See program below. I cannot get it render a node as Selected (the text should change to "Sel: " + text).

      import javafx.application.Application;
      import javafx.scene.Scene;
      import javafx.scene.control.TreeCell;
      import javafx.scene.control.TreeItem;
      import javafx.scene.control.TreeView;
      import javafx.scene.layout.VBox;
      import javafx.stage.Stage;
      import javafx.util.Callback;

      public class JavaFXApplication4 extends Application {

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

        @Override
        public void start(Stage primaryStage) {
          VBox root = new VBox();
          Scene scene = new Scene(root, 500, 300);
          root.getChildren().add(makeHelpTopicsTree());
          primaryStage.setScene(scene);
          primaryStage.show();
        }

        public TreeView<String> makeHelpTopicsTree() {
          TreeItem<String> root = new TreeItem<>("Root Node");
          root.setExpanded(true);

          TreeItem<String> node1 = new TreeItem<>("Tree Node 1");
          TreeItem<String> node2 = new TreeItem<>("Tree Node 2");

          TreeItem<String> node3 = new TreeItem<>("Tree Node 3");
          node3.setExpanded(true);
          TreeItem<String> node4 = new TreeItem<>("Tree Node 4");
          TreeItem<String> node5 = new TreeItem<>("Tree Node 5");
          node3.getChildren().addAll(node4, node5);
          root.getChildren().addAll(node1, node2, node3);

          treeViewHelp = new TreeView<>(root);
          treeViewHelp.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
            @Override
            public TreeCell<String> call(TreeView<String> treeViewHelp) {
              return new MyTreeCell();
            }
          });

          treeViewHelp.getSelectionModel().select(node4);

          return treeViewHelp;
        }

        public class MyTreeCell extends TreeCell<String> {
          @Override
          public void updateItem(String text, boolean empty) {
            super.updateItem(text, empty);

            if(!empty) {
              setText(isSelected() ? "Sel: " + text : text);
            }
          }
        }

        private TreeView<String> treeViewHelp;
      }

            jgiles Jonathan Giles
            jhendrikx John Hendrikx
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported: