Reputation: 55
I have some JavaFX components declared in my fxml file.
and how do I get the values of the fields (Username, Password) when the button is pressed? (To perform the login).
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
stage.setTitle("Login");
stage.setScene(new Scene(root,400,300));
stage.show();
or is this the complete wrong way to do it?
My Questions:
EDIT : https://hastebin.com/qexipogoma.xml <- My FXML fie and my controller
Upvotes: 2
Views: 7892
Reputation: 82461
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
}
}
Upvotes: 4
Reputation: 464
Scene scene = stage.getScene();
Button btn = (Button) scene.lookup("#myBtnID");
TextField txt = (TextField ) scene.lookup("#myTxtID");
you're looking for:
txt.getText();
and
btn.setOnAction( lambda here );
Documentation:
EDIT: declare ids this way
<TextField fx:id="myTxtID" ... />
Upvotes: 6
Reputation: 2217
Try using SceneBuilder. It will produce an FXML file and a compatible controller. This will give you a good start.
Upvotes: 1