Is it a good idea to declare all fields in the fxml file?
This depends on what you need. In this case you do not need to add/remove any parts of the scene dynamically. You'll probably replace the window/scene on a successful login. There should not be any issue with creating this scene via fxml.
How do I get the objects to acces the values?
Use a controller with the fxml and access the values via this controller.
<AnchorPane fx:controller="mypackage.LoginController" ...>
<children>
...
<TextField fx:id="username" ... />
...
<PasswordField fx:id="password" ... />
...
<Button onAction="#login" ... />
</children>
</AnchorPane>
package mypackage;
...
public class LoginController {
private boolean login = false;
@FXML
private TextField username;
@FXML
private PasswordField password;
@FXML
private void login() {
// regular close the login window
login = true;
password.getScene().getWindow().hide();
}
public String getUsername() {
return username.getText();
}
public String getPassword() {
return password.getText();
}
public boolean isLogin() {
return login;
}
public void resetLogin() {
// allow reuse of scene for invalid login data
login = false;
}
}
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Stage stage = new Stage(new Scene(loader.load()));
LoginController controller = loader.getController();
boolean loginSuccess = false;
stage.showAndWait();
if (controller.isLogin()) {
if (checkLogin(controller.getUsername(), controller.getPassword())) {
// handle login success
} else {
// handle invalid login
}
}