Run the given code below. You will find that the 2nd item in TreeView does not receive focus, despite calling:
treeView.getFocusModel().focus(1);
This only happens when you change a scene (but not replace it completely). Work-arounds to make this work as expected:
1) Replace the entire scene...
2) Wrap the focus(1) call in Platform.runLater() -- despite already being on the JavaFX thread.
I would expect neither of the work-arounds to be required to get this to work directly.
public class TreeItemFocusTest extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
VBox vbox = new VBox();
BorderPane borderPane = new BorderPane();
Button button = new Button("Sometihng to grab focus");
final TreeView<String> treeView = new TreeView<String>();
TreeItem<String> root = new TreeItem<String>("Root");
root.setExpanded(true);
treeView.setRoot(root);
root.getChildren().add(new TreeItem<String>("Item 1"));
root.getChildren().add(new TreeItem<String>("Item 2"));
root.getChildren().add(new TreeItem<String>("Item 3"));
root.getChildren().add(new TreeItem<String>("Item 4"));
vbox.getChildren().addAll(button, treeView);
Scene scene = new Scene(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
// Change the borderpane contents here
borderPane.setCenter(vbox);
// Give desired item the focus
treeView.requestFocus();
treeView.getFocusModel().focus(1);
}
}
treeView.getFocusModel().focus(1);
This only happens when you change a scene (but not replace it completely). Work-arounds to make this work as expected:
1) Replace the entire scene...
2) Wrap the focus(1) call in Platform.runLater() -- despite already being on the JavaFX thread.
I would expect neither of the work-arounds to be required to get this to work directly.
public class TreeItemFocusTest extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
VBox vbox = new VBox();
BorderPane borderPane = new BorderPane();
Button button = new Button("Sometihng to grab focus");
final TreeView<String> treeView = new TreeView<String>();
TreeItem<String> root = new TreeItem<String>("Root");
root.setExpanded(true);
treeView.setRoot(root);
root.getChildren().add(new TreeItem<String>("Item 1"));
root.getChildren().add(new TreeItem<String>("Item 2"));
root.getChildren().add(new TreeItem<String>("Item 3"));
root.getChildren().add(new TreeItem<String>("Item 4"));
vbox.getChildren().addAll(button, treeView);
Scene scene = new Scene(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
// Change the borderpane contents here
borderPane.setCenter(vbox);
// Give desired item the focus
treeView.requestFocus();
treeView.getFocusModel().focus(1);
}
}