问题
I try to implement an TreeView in my JavaFX App. But unfortenatly no items are showed, but i cannot find an issue. I search for some example and did it like them.
I put an TreeView Control to my FXML File in SceneBuilder and selected the ControllerClass which was generated and slected the Treeview field from this class as an id for the TreeView Control in SceneBuilder.
That's my Controller code:
public class MainSceneController implements Initializable {
@FXML
TreeView<String> treeview;
@FXML
Button btn;
@Override
public void initialize(URL url, ResourceBundle rb) {
TreeItem<String> root = new TreeItem<>("root");
for(int i = 0; i < 10; i++) {
TreeItem<String> child = new TreeItem<>("Children " + i);
root.getChildren().add(child);
}
root.setExpanded(true);
this.treeview = new TreeView<>(root);
treeview.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
}
@FXML
public void addTreeViewItem() {
}
@FXML
private void showAddStreamDialog() {
try {
Parent p;
p = FXMLLoader.load(getClass().getResource("AddStream.fxml"));
Scene s = new Scene(p);
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(s);
stage.show();
} catch (IOException ex) {
Logger.getLogger(MainSceneController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Any idea's whats wrong?
回答1:
You shouldn't assign new instance to the this.treeview
because this field was already initialized by the FXLoader.
So instead of this.treeview = new TreeView<>(root);
you need simply to set the root item this.treeview.setRoot(root);
来源:https://stackoverflow.com/questions/33549795/javafx-treeview-shows-no-items