Java FX changing value of Label from different sce

2020-04-18 07:42发布

问题:

I have two scenes. The first scene invokes second scene using the following code.

@FXML
private void confirmation(ActionEvent event) throws IOException{
 Stage confirmation_stage;
 Parent confirmation;
 confirmation_stage=new Stage();
 confirmation=FXMLLoader.load(getClass().getResource("Confirmation.fxml"));
 confirmation_stage.setScene(new Scene(confirmation));
 confirmation_stage.initOwner(generate_button.getScene().getWindow());
 confirmation_stage.show();
 }

There is a label in "Confirmation.fxml" called "Proceed".

I need to change the content of that label from within this function and return the result(true/false). Help?

回答1:

Create a ConfirmationController for the FXML. From the controller, expose a method which allows you to pass data (string) to set to the label.

public class ConfirmationController implements Initializable {

    ...
    @FXML
    private Label proceed;
    ...
    public void setTextToLabel (String text) {
         proceed.setText(text);
    }
    ...
}

Inside your method where you are loading the FXML, you can have :

...
FXMLLoader loader = new FXMLLoader(getClass().getResource("Confirmation.fxml"));
confirmation = loader.load();
ConfirmationController controller = (ConfirmationController)loader.getController();
controller.setTextToLabel("Your Text"); // Call the method we wrote before
...


回答2:

Labels in FXML have a setText method. So for your case the "Proceed" label will look something like:

Proceed.setText("The new text");

As for the second part of the question, I'm not 100% sure as to what you are asking. I don't really see any case for the function to return true or false.



回答3:

Assuming that you have a controller called:confirmation_controller.java'. inside that controller, you have a public method getProceedLabel() that returns a reference for the label called Proceed. you can try the following code:

 Stage confirmation_stage;
 Parent confirmation;
 confirmation_stage=new Stage();
 FXMLLoader loader = new FXMLLoader(getClass().getResource("Confirmation.fxml"));
 confirmation = loader.load();
 confirmation_controller controller = loader.getController();
 Label label = controller.getProceedLabel();
 label.setText("..."):
 confirmation_stage.setScene(new Scene(confirmation));
 confirmation_stage.initOwner(generate_button.getScene().getWindow());
 confirmation_stage.show();