我是JavaFX的新手,在做项目时,我试图切换屏幕。我正在考虑将相应的AnchorPane可见性设置为true或false,并且从另一个Controller访问AnchorPane时遇到问题。我试图使AnchorPane静态,但它提供了NullPointerException。
这是我的代码。
控制器类
public class Controller {
@FXML
AnchorPane signInPane;
@FXML
private TextField usernameForSignIn;
@FXML
private PasswordField password;
@FXML
private Button signIn;
@FXML
private Button registration;
@FXML
void initialize() {
registration.setOnAction(event -> {
signInPane.setVisible(false);
SignUpController.registerPane.setVisible(true);
});
signIn.setOnAction(event -> {
String usernameText = usernameForSignIn.getText().trim();
String passwordText = password.getText().trim();
if(!usernameText.equals("") && !passwordText.equals("")) {
loginUser(usernameText, passwordText);
} else {
System.out.println("Empty login and/or password");
}
});
}
private void loginUser(String usernameText, String passwordText) {
}
}
SignUpController类
public class SignUpController {
@FXML
static AnchorPane registerPane;
@FXML
private TextField email;
@FXML
private PasswordField pass;
@FXML
private Button signUp;
@FXML
private TextField fname;
@FXML
private TextField lname;
@FXML
private TextField username;
@FXML
private RadioButton radioMale;
@FXML
void initialize() {
signUp.setOnAction(event -> {
signUpNewUser();
});
}
private void signUpNewUser() {
DatabaseHandler databaseHandler = new DatabaseHandler();
String firstName = fname.getText();
String lastName = lname.getText();
String usname = username.getText();
String password = pass.getText();
String e_mail = email.getText();
String gender = "";
if(radioMale.isSelected()) {
gender = "Male";
} else {
gender = "Female";
}
User user = new User(firstName,lastName,usname,password,e_mail,gender);
databaseHandler.signUpUser(user);
}
}
我试图解决这样的问题,但是它关闭了窗口并打开了一个新窗口。
registration.setOnAction(event -> {
registration.getScene().getWindow().hide();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample/view/signUp.fxml"));
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Parent root = loader.getRoot();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.showAndWait();
// signInPane.setVisible(false);
});
答案 0 :(得分:0)
创建一个窗口并重复使用,而不是每次都创建一个新窗口。然后,您可以只检查它是否显示,也可以禁用显示时显示的控件。
答案 1 :(得分:0)
类似这样的方法将确保在initalize()之前加载FXML。您不必隐藏您的AnchorPane,因为实例已经加载。隐藏从FXML创建的项目通常会导致错误。
public class Controller {
@FXML
Button button_CustomerInfo;
@FXML
Button button_A1Child;
@FXML
BorderPane bPane;
@FXML
ToggleGroup tog;
Parent r1;
Parent r2;
// CREATE SOMETHING LIKE THIS
// THIS SAMPLE CODE USES THE SAME BORDERPANE
// AND THE CENTER OF THE BORDERPANE
// IS CHANGED WHEN A BUTTON IS PRESSED
{
try {
r1 = FXMLLoader.load(getClass().getResource("SecondSreen.fxml"));
r2 = FXMLLoader.load(getClass().getResource("FirstScreen.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void initialize() {
button_CustomerInfo.setOnAction(e-> {
bPane.setCenter(r2);
});
button_A1Child.setOnAction(e-> {
bPane.setCenter(r1);
});
}
}