im trying to add some items to my View Table . im creating a ObservableList and pass it to the setItem method but it throws null Exception .
Here is the latest attempt :
javafx.scene.control.TableView table = controller.friendsList;
/*
the controller.friendList is defined as Below :
@FXML
public javafx.scene.control.TableView friendsList;
*/
ObservableList friendData = FXCollections.observableArrayList();
for(Client friend : friends )
{
friendData.add(friend.getUsername());
}
//The friendData is fine ( according to the debugging ) it includes 2 Strings
table.setItems(friendData);
table.setEditable(false);
table.setVisible(false);
table.setVisible(true);
}
whats wrong with the code ?
EDIT:
now i get the controller from the FXMLLoader as the answere says . but it's still the same . all the field with the @FXML anotation are still null .
here is how i get the controller :
public userSceneController controller;
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(getClass().getResource("userScene.fxml"));
controller = (userSceneController) fxmlLoader.getController();
Since your TableView
is a @FXML
-annotated field in the controller, it is initialized in the controller instance created by the FXMLLoader
. In other words, presumably at some point in the code you didn't actually show, you create an FXMLLoader
and call load()
on it. As part of that load
process, the FXMLLoader
creates an instance of the controller and initializes the @FXML
-annotated fields with references to the controls displayed in the UI.
You are presumably intending to configure the table view that is displayed in the UI; in order to do that, you need to reference the controller that the FXMLLoader
created for you.
However, what you actually do in your code is to create a new controller instance:
Controller controller = new Controller();
Obviously since this in not the controller created as part of the FXMLLoader.load()
process, it never had its friendsList
field initialized.
Instead, you need to retrieve the controller instance from your FXML loader. In order to do this, you must create an FXMLLoader
with a location properly set, and then use the instance method FXMLLoader.load()
, not the static method FXMLLoader.load(URL)
:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("userScene.fxml"));
Parent root = (Parent) fxmlLoader.load();
controller = (userSceneController) fxmlLoader.getController();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.