I have few scenes in my Java project and one problem that I really don't know how to solve. First scene called "Zadanie". There are TextFields and ComboBoxes in this first scene called "Zadanie". So, as you can see in image, I wrote some numbers in TextFields and choosed some options in ComboBoxes. Then I switched on other scene by clicking on "Vypočítať" (button up). And then I switched back on first scene "Zadanie", but everything in TextFields and ComboBoxes is gone. Back on first scene "Zadanie". Please give me some example of code or something how to keep those in first scene. Thank you.
The problem is that when you switch screens, the object that represents the screen is disposed of. So any variables such as user input is also disposed of. when you switch back to the screen, it's a different object but of the same type. This means the values of variables such as user input is freshly instantiated/initialized.
Solution: Create some global variables (for example, variables in Main, but you should use different classes for programming practices sake) that store this information. When the user clicks to switch screens, but before the screen is actually switched (unloaded), store any user input in global variables. Then when the screen is switched back to, reload those variables into the fields from the global variables.
Global.java
class Global {
public static String nameFieldValue;
public static String ageFieldValue;
}
PersonForm.java
class PersonForm extends BorderPane {
Button closeButton;
TextField nameField;
TextField ageField;
public PersonForm() {
this.nameField = new TextField(...);
this.ageField = new TextField(...);
this.closeButton = new Button("Close Window");
// set layouts of buttons here.
if (Global.nameFieldValue != null) {
this.nameField.setText(Global.nameFieldValue);
}
if (Global.passwordFieldValue != null) {
this.passwordField.setText(Global.passwordFieldValue);
}
PersonForm thisForm = this; // So that EventHandler cna use this.
this.closeButton.setOnAction(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Global.nameFieldValue = thisForm.nameField.getText();
Global.passwordFieldValue = thisForm.passwordField.getText();
// switch screens.
}
});
}
}