JavaFX Treeview shows no items - java

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?

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);

Related

Send data back and forth between controllers JavaFX FXML

all the questions I found around here answered how to send data from one controller to another. However, I don't know how to return another value from the second controller to the first one. Basically, send data back and forth while the first controller is still opened.
Main class:
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Screen1.fxml"));
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.setTitle("Screen 1");
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Screen 1 controller:
public class Screen1Controller {
#FXML
TextField textFieldScreen1;
#FXML
Button buttonScreen1;
#FXML
Label labelScreen1;
#FXML
private void initialize() {
buttonScreen1.setOnAction((event) -> {
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Screen2.fxml"));
Scene scene = new Scene(loader.load());
Stage stage = new Stage();
//Send data to Screen 2
Screen2Controller controller2 = loader.getController();
controller2.receiveTextFromScreen1(textFieldScreen1.getText());
stage.setTitle("Screen 2");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
Screen 2 controller:
public class Screen2Controller {
#FXML
TextField textFieldScreen2;
#FXML
Button buttonScreen2;
#FXML
Label labelScreen2;
#FXML
private void initialize() {
buttonScreen2.setOnAction((event) -> {
Stage currentStage = (Stage) buttonScreen2.getScene().getWindow();
currentStage.close();
});
}
public void receiveTextFromScreen1(String stringScreen1){
labelScreen2.setText(stringScreen1);
}
}
I have tried to use the same strategy (create a method in Screen1Controller and instantiate Screen1Controller in the second controller) with the following code but it didn't work.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Screen2.fxml"));
//Send data to Screen 1
Screen1Controller controller1 = loader.getController();
controller1.receiveTextFromScreen2(textFieldScreen2.getText());
Also, related to this matter (I'm assuming) a second question: how would I update the second view while I change the TextField in controller 1 without creating a new window everytime I click the button (i.e using the same second view instance)?
Any help will be greatly appreciated!
Create a constructor
public Screen1Controller {
Arrow the parameters
}
and when you call the controller, you parse the parameter:
void on2players(ActionEvent event) throws IOException {
client.out.println("ACTION NEWGAME 2 4");
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/boardscreen.fxml"));
loader.setController(new Screen1Controller(parameter);
Parent root = loader.load();
Scene scene= new Scene(root);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
}
public class Screen1Controller implements Initializable {
public Screen1Controller() {
//parameters
}
#Override
public void initialize(URL location, ResourceBundle resources) {
switch(numberOfPlayers){
case 2:
//TODO...creating board for 2 players
case 3:
//TODO creatinf board for 3 players
}
}
If you do this, you force the fxml loader to call the controller. NOTE: You should get the controller inside .FXML

Trouble passing parameters between scenes

I'm having a problem with this code I am writing. The project is a password keeper app, and for this current sprint I created a Password model and another class to hold an ArrayList of Passwords called PasswordList. I've created a PasswordList object in every controller class as a private variable and pass it along by loading the controller of the next scene and setting the PasswordList with the current controller's PasswordList (so that the same list is passed throughout the whole project). However, when creating a new Password object, adding it to this PasswordList, then switching scenes, the PasswordList is null.
So, I have a PasswordUI which is the viewer, and from there a user can click on the "Add" button to view the CreatePasswordUI. I've tested to make sure that the password is created and added successfully to the PasswordList by printing it to the console and using the debugger, and everything checks out. I can even go back to add another password, and the list still has all the previous Password objects created. Yet, in the PasswordUI, the PasswordList is still coming up as null even though I am passing the PasswordList from the previous scene.
I am stuck and do not know what to do.
public class PasswordUIController implements Initializable {
private PasswordList passList;
/**
* Initializes the controller class.
*/
#FXML
TreeTableView passwordInfo;
#FXML
TreeTableColumn<String,String> acctColumn;
#FXML
Parent root;
#FXML
private void backButtonAction(ActionEvent event) throws Exception {
Stage stage = (Stage) root.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenuUI.fxml"));
Pane mainMenuUI = (Pane)loader.load();
MainMenuController controller = loader.<MainMenuController>getController();
controller.setPassList(passList);
Scene scene = new Scene(mainMenuUI);
stage.setTitle("Main Menu");
stage.setScene(scene);
stage.show();
}
#FXML
private void addButtonAction(ActionEvent event) throws Exception {
Stage stage = (Stage) root.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("CreatePasswordUI.fxml"));
Pane createPassUI = (Pane)loader.load();
CreatePasswordUIController controller = loader.<CreatePasswordUIController>getController();
controller.setPassList(passList);
Scene scene = new Scene(createPassUI);
stage.setTitle("Create Password");
stage.setScene(scene);
stage.show();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
PasswordList pList = passList;
if (pList != null) {
ArrayList<Password> thePasswords = pList.getPasswordList();
TreeItem<String> passwords = new TreeItem<>("Passwords");
for (int i = 0; i < thePasswords.size(); i++) {
Password thePass = thePasswords.get(i);
//Creating tree items
TreeItem<String> username = new TreeItem<>("Username: " + thePass.getUsername());
TreeItem<String> password = new TreeItem<>("Password: " + thePass.getPassword());
TreeItem<String> comment = new TreeItem<>("Comment: " + thePass.getComment());
//Creating the root element
TreeItem<String> account = new TreeItem<>(thePass.getAccount());
account.setExpanded(true);
//Adding tree items to the root
account.getChildren().setAll(username, password, comment);
passwords.getChildren().add(account);
}
//Creating a column
acctColumn = new TreeTableColumn<>("Account");
//Defining cell content
acctColumn.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<String, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<String, String> param){
return new SimpleStringProperty(param.getValue().getValue());
}
});
//Creating a tree table view
passwordInfo = new TreeTableView<>();
passwordInfo.setRoot(passwords);
passwordInfo.getColumns().add(acctColumn);
} else {
}
}
/**
* #return the passList
*/
public PasswordList getPassList() {
return passList;
}
/**
* #param passList the passList to set
*/
public void setPassList(PasswordList passList) {
this.passList = passList;
}
}
public class CreatePasswordUIController implements Initializable {
private PasswordList passList;
/**
* Initializes the controller class.
*/
#FXML
Parent root;
#FXML
TextField accountTxt;
#FXML
TextField usernameTxt;
#FXML
TextField passwordTxt;
#FXML
TextField passwordTxt2;
#FXML
TextArea commentArea;
#FXML
TextField passwordGeneratorTxt;
#FXML
Label rating;
#FXML
Label matching;
#FXML
Label incorrect;
#FXML
private void backButtonAction(ActionEvent event) throws Exception {
Stage stage = (Stage) root.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenuUI.fxml"));
Pane mainMenuUI = (Pane)loader.load();
MainMenuController controller = loader.<MainMenuController>getController();
controller.setPassList(passList);
Scene scene = new Scene(mainMenuUI);
stage.setTitle("Main Menu");
stage.setScene(scene);
stage.show();
}
#FXML
private void submitButtonAction(ActionEvent event) throws Exception {
String account = accountTxt.getText();
String username = usernameTxt.getText();
String password = passwordTxt.getText();
String password2 = passwordTxt2.getText();
String comment = commentArea.getText();
if (password.equals(password2) && username.length()>2) {
PasswordList pList = passList;
Password thePass = new Password(account, username, password, comment);
pList.addPassword(thePass);
Stage stage = (Stage) root.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("PasswordUI.fxml"));
Pane passwordUI = (Pane)loader.load();
PasswordUIController controller = loader.<PasswordUIController>getController();
controller.setPassList(pList);
Scene scene = new Scene(passwordUI);
stage.setTitle("Password");
stage.setScene(scene);
stage.show();
} else {
incorrect.setVisible(true);
}
}
#FXML
private void generateButtonAction(ActionEvent event) {
PasswordGenerator passGen = new PasswordGenerator();
String password = passGen.generatePassword(true);
passwordGeneratorTxt.setText(password);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
PasswordRater rater = new PasswordRater();
passwordTxt.textProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldVal,Object newVal) {
String password = passwordTxt.getText();
rater.setPassword(password);
String ratingStr = rater.displayLevel();
rating.setText(ratingStr);
rating.setVisible(true);
if (passwordTxt.getText().equals(passwordTxt2.getText()) && !password.equals("")) {
matching.setText("Good!");
}
else
{
matching.setText("Passwords do not match.");
}
}
});
passwordTxt2.textProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldVal,Object newVal) {
String password = passwordTxt.getText();
String password2 = passwordTxt2.getText();
if (password.equals(password2) && !password.equals("")) {
matching.setText("Good!");
} else {
matching.setText("Passwords do not match.");
}
matching.setVisible(true);
}
});
}
/**
* #return the passList
*/
public PasswordList getPassList() {
return passList;
}
/**
* #param passList the passList to set
*/
public void setPassList(PasswordList passList) {
this.passList = passList;
}
}
The problem with having a new password list in every controller is that everytime a new instance is created , you are basically Looking at a singleton approach .
Either you can try singleton like only one object is created throughout the application or for a simpler approach you can have a single static list in your main class and then reuse it in the subsequent contorllers.
If you specify the controller in the fxml file using the fx:controller attribute and do not specify a controller factory, FXMLLoader procedes as follows:
load() method is entered
when the fx:controller attribute is read a new instance of the controller class specified in the attribute value is created.
Any elements with a fx:id attributes are injected to the approprieate fields of the controller instance.
The controller's initialize method is called, if there is one
load() completes returning the element created for the root element of the fxml file
For
FXMLLoader loader = new FXMLLoader(getClass().getResource("CreatePasswordUI.fxml"));
Pane createPassUI = (Pane)loader.load();
CreatePasswordUIController controller = loader.<CreatePasswordUIController>getController();
controller.setPassList(passList);
to work however you'd need a different order of operations:
1.
2.
3.
5.
controller.setPassList(passList);
4.
If you want create the controller this way, move the code for initializing the TreeTableView to the setPassList method.
BTW: I'm pretty sure creating a new TreeTableView is not what you want. Instead you should set the data to the existing TreeTableView created by the FXMLLoader:
PasswordUIController
#Override
public void initialize(URL url, ResourceBundle rb) {
// displaying the item itself in the TreeTableColumn defys
// the purpose of Tree**Table**View, but we'll ignore this here
acctColumn.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<String, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<String, String> param){
return new SimpleStringProperty(param.getValue().getValue());
}
});
}
public void setPassList(PasswordList passList) {
if (passList == null) {
throw new IllegalArgumentException();
}
this.passList = passList;
ArrayList<Password> thePasswords = passList.getPasswordList();
TreeItem<String> passwords = new TreeItem<>("Passwords");
for (int i = 0; i < thePasswords.size(); i++) {
Password thePass = thePasswords.get(i);
//Creating tree items
TreeItem<String> username = new TreeItem<>("Username: " + thePass.getUsername());
TreeItem<String> password = new TreeItem<>("Password: " + thePass.getPassword());
TreeItem<String> comment = new TreeItem<>("Comment: " + thePass.getComment());
//Creating the root element
TreeItem<String> account = new TreeItem<>(thePass.getAccount());
account.setExpanded(true);
//Adding tree items to the root
account.getChildren().setAll(username, password, comment);
passwords.getChildren().add(account);
}
// set content of the TreeTableView
passwordInfo.setRoot(passwords);
}
There are other ways of passing data to a fxml controller. You can find some good answers here: Passing Parameters JavaFX FXML

JavaFX TableView Issues Adding Rows + Organizing Multi Controller and FXML App

I'm new to JavaFX and I've been at this code for about 8 hours now and I've become a bit delusional with the code. My two main problems are:
Can't add new items to the TableView using my popUp box display().
Feels messy and unorganized. Any tips for better communication between FXML and Controllers? (Again I'm new so it could be that I've stared too long at it)
My main class
public class Main extends Application {
public static Stage primaryStage;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage window) throws Exception {
try {
primaryStage = new Stage();
window = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("Fissto.fxml"));
Scene scene = new Scene(root);
window.setTitle("Fissto - the File Storage App!");
window.setScene(scene);
window.show();
}catch(Exception e){
e.printStackTrace();
}
// C.setLibraryStage();
}
}
My main Controller class (I have two sub ones that connect in the Fissto.fxml)
public class Controller implements Initializable{
Main main;
#FXML LibraryController libraryController = new LibraryController();
#FXML MergePageController mergePageController = new MergePageController();
private AddImageController addImageController = new AddImageController();
#FXML public void initialize(URL location, ResourceBundle resources){
System.out.println("View is now loaded!");
main = new Main();
libraryController.init(this);
mergePageController.init(this);
addImageController.init(this);
}
//Interface Initialization
public void setMergeStage() throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Controllers/MergePage.fxml"));
Scene scene = new Scene(root);
main.primaryStage.setScene(scene);
}
public void setLibraryStage() throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Controllers/LibraryPage.fxml"));
Scene scene = new Scene(root);
main.primaryStage.setScene(scene);
}
//Closing a window
public void closeWindow(){
main.primaryStage.close();
}
}
And finally the controller for the page that holds the TableView
public class LibraryController {
private Controller main;
//Library TableView Controllers
#FXML public TableView<Image> library;
#FXML private TableColumn<Image, String> NameColumn = new TableColumn<>();
#FXML private TableColumn<Image, ArrayList<String>> TagsColumn = new TableColumn<>();
#FXML private TableColumn<Image, String> CommentsColumn = new TableColumn<>();
#FXML private TableColumn<Image, String> FileLocationColumn = new TableColumn<>();
#FXML private TableColumn<Image, Integer> PointsColumn = new TableColumn<>();
public void init(Controller main){
System.out.println("LibraryPage Loading");
this.main = main;
addDataToColumns();
library = new TableView<>();
library.getItems().setAll(getImages());
System.out.println("LibraryPage Loaded");
}
//Initializes the column titles
private void addDataToColumns(){
NameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
TagsColumn.setCellValueFactory(new PropertyValueFactory<>("tags")); //TODO Convert to String format
CommentsColumn.setCellValueFactory(new PropertyValueFactory<>("comments"));
FileLocationColumn.setCellValueFactory(new PropertyValueFactory<>("filelocation"));
PointsColumn.setCellValueFactory(new PropertyValueFactory<>("points"));
}
//Gets all of the images
private ObservableList<Image> getImages() {
//TODO: Add where to actually get the data from
ObservableList<Image> images = FXCollections.observableArrayList();
String s = "Dog, Cat, Jumping Jack,";
ArrayList<String> list = Image.getTagOrganizer(',', s);
images.add(new Image("Test", list, "Comment", "No File Location, yet!", 10));
String k = "Calculus, Complex Numbers, Hard dude,";
ArrayList<String> list2 = Image.getTagOrganizer(',', k);
images.add(new Image("Number2", list2, "I love MathClub", "No File Location, yet!", -10));
return images;
}
This last class is the popup menu that takes in input to put in the GridPane
public class AddImageController {
private Controller main;
public void init(Controller main){
System.out.println("ImagePage Loaded");
this.main = main;
}
//Submitting an image to the library from the AddImagePage
public TextField nameInput;
public TextField tagsInput;
public TextField commentInput;
public TextField pointsInput;
public Label errorMessage;
/** TODO: Make it so that it writes to file then theoretically, the main controller should read from file every so often
* Main functionality for adding the information from the form to the database */
public void submitImage(){
if(!(nameInput.getText().trim().isEmpty()) && !(tagsInput.getText().trim().isEmpty()) && !(pointsInput.getText().trim().isEmpty())) {
if (isInt(pointsInput)) {
// System.out.print("Sent to database, *whoosh!*");
LibraryController c = new LibraryController();
ArrayList<String> s = Image.getTagOrganizer(',', tagsInput.getText());
Image image = new Image(nameInput.getText(), s, commentInput.getText(),"Location Needed", Integer.parseInt(pointsInput.getText()));
c.library.getItems().add(image);
clearInputs();
}
}else {
errorMessage.setText("Fill every field");
}
}
//Clears the input fields in the AddImagePage
public void clearInputs(){
nameInput.clear();
tagsInput.clear();
commentInput.clear();
pointsInput.clear();
errorMessage.setText("");
}
//Submission format verifiers
private boolean isInt(TextField input){
try{
int i = Integer.parseInt(input.getText());
errorMessage.setText("");
return true;
}catch (NumberFormatException e){
System.out.println("Oh no: " + input.getText() + " is not an integer");
errorMessage.setText("Points must be a number");
return false;
}
}
//Image Selection Handler
public void imageSelectionHandler(){
}
}
I understand it may be hard to read, so any feedback on how to make it easier to read in the future is much appreciated.

JavaFX - How to add Item to ListView from different Stage?

How can i add an item to an already existing ListView from a different Stage (Window).
Basically i just want to add Text to the ListView from Window 2 to the ListView in Window 1.
Thanks in advance.
Sorry i forgot this is what i've got so far in my controller class: (im a beginner in javafx ..)
(below i try to add a String to the ListView but this doesnt work...and i dont know why )
public class ClientGUIController implements Initializable {
#FXML private Text usernameText;
#FXML private Button cancelButtonNewDate;
#FXML private TextField newDateTitel,newDateJahr;
#FXML private TextArea newDateNotiz;
#FXML private ComboBox<String> newDateTag,newDateMonat,newDateStunde,newDateMinute;
#FXML private ListView<String> terminListView;
private ObservableList<String> termine =
FXCollections.observableArrayList();
private ObservableList<String> listItems = FXCollections.observableArrayList("Add Items here");
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public Text getUsernameText() {
return usernameText;
}
public void setUsernameText(String username ) {
this.usernameText.setText(username);
terminListView.setItems(listItems);
listItems.add("test");
}
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("newDate.fxml"));
// FXMLLoader loader = new FXMLLoader();
// root = (Parent) loader.load(getClass().getResource("NewDate.fxml").openStream());
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
// sceneNewDate.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}
public void createNewDate() throws IOException {
// Termine meinTermin = new Termine(Integer.parseInt(newDateTag.getValue()), Integer.parseInt(newDateMonat.getValue()), Integer.parseInt(newDateJahr.getText()), newDateTitel.getText(), newDateNotiz.getText(),
// Integer.parseInt(newDateStunde.getValue()), Integer.parseInt(newDateMinute.getValue()));
//Add item to ListView
listItems.add("test"); <- this doesnt work
}
public void closeDialogue(){
Stage stage = (Stage) cancelButtonNewDate.getScene().getWindow();
stage.close();
}
}
One way to do this is to pass listItems to the controller for newDate.fxml, so it can just add to that list. So, assuming the controller class for newDate.fxml is NewDateController, you would do something like:
public class NewDateController {
private ObservableList<String> data ;
public void setData(ObservableList<String> data) {
this.data = data ;
}
// other code as before...
// button handler:
#FXML
private void handleButtonPress() {
data.addItem("test");
}
}
Then in your ClientGUIController, load the fxml like this:
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("newDate.fxml"));
root = loader.load();
NewDateController controller = loader.getController();
controller.setData(listItems);
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}

Problems with list view after updating to java 8

After updating to Java 8, i got problems displaying content of list view
public class TestController extends AnchorPane implements Initializable {
#FXML
private ListView<String> listView;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setApp() {
setContent();
}
/**
* Set content in list
*/
private void setContent() {
ObservableList<String> items = FXCollections.observableArrayList();
items.add("1");
items.add("2");
listView.setItems(items);
}
}
With Java 7 this gives me a list with values. After update to java 8, it gives me a empty frame.
Thanks James_D, here is the code you asked for
public void goToTest() {
try {
TestController test = (TestController) replaceSceneContent("/fxml/test.fxml");
test.setApp();
} catch (Exception ex) {
System.out.println("Error loading: " + ex + " - " + ex.getMessage());
}
}
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
InputStream in = MainApp.class.getResourceAsStream(fxml);
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(MainApp.class.getResource(fxml));
AnchorPane page;
try {
page = (AnchorPane) loader.load(in);
} finally {
in.close();
}
Scene scene = new Scene(page);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(resizable);
return (Initializable) loader.getController();
}
listView = new ListView<>(items);
will not work; it will create a new ListView and populate it, whereas what you want to do is populate the ListView you created in your FXML.
listView.setItems(items);
is the correct code.
(I assume you really have public class TestController implements Initializable, not public class test implements Initializable.)
So the following should work:
private void setContent() {
ObservableList<String> items = FXCollections.observableArrayList();
items.add("1");
items.add("2");
listView.setItems(items);
}
Your FXMLLoader code is a little unusual in that you set a location (URL) but then use the load(InputStream) method to load. I'd be surprised if this fixed it, but the usual way would be:
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
// not needed:
// InputStream in = MainApp.class.getResourceAsStream(fxml);
// Not really needed, this is the default:
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(MainApp.class.getResource(fxml));
AnchorPane page;
// instead of this:
// try {
// page = (AnchorPane) loader.load(in);
// } finally {
// in.close();
// }
// just this (since you have set the location):
page = loader.load();
Scene scene = new Scene(page);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(resizable);
return (Initializable) loader.getController();
}
(Random guess: did you accidentally make listView static in the Controller?)

Categories