JAVAFX How to change the label after FXML is built?

Asked

Viewed 441 times

-1

I have a label on Scene B. I want to change this label when the user clicks on the "Login" button on the first screen. I tried to do this in my project with the usuario.setText() (user is the label name), but as the label is built after the change command, the change is not made and an error occurs. How do I change the label after it has been built and exists in Javafx?

@FXML
void RegisterLogin(ActionEvent event) // Evento ao clicar no botão no Scene A.

{

 MessageController msgcont = new MessageController(); //Instanciação do Scene B;
 msgcont.usuario.setText("Teste"); //Label do Scene B;

}

The amendment msgcont.usuario.setText("Teste"); does not occur.

Thank you.

  • What is your code? What error appears? Without this information it will be difficult for anyone to give a good answer

  • I edited it. I’m sorry.

  • No problem, no need to apologize

1 answer

0

In your Messagecontroller Application class, create a reference to your Controller class so you can change and pass objects to it, you can do something like this:

public class Principal extends Application {

//Criando um atributo para acessar o Controller da aplicação
public static PrincipalController controller ;

@Override
public void start(Stage stage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(this.getClass().getSimpleName() + ".fxml"));
    Parent root = (Parent) loader.load();
    this.controller = (PrincipalController) loader.getController();
    Scene scene = new Scene(root)
    stage.setScene(scene);
    stage.show();
}

Then, in your Controller class, create an attribute to receive the object you want to change. In your case it would be a String to change the Label.

private String usuarioLogado

In the Login Controller, after checking the user credentials, please enter the Messagecontroller class the desired variable, and seven its value:

@FXML
private void actionBtnLogar(ActionEvent event) {
//....
    try {
        usuario = this.verificaCredencias(login, senha);
        if (usuario) {
           Principal prin = new Principal ();
           prin.start(new Stage());
           prin.controller.setUsuarioLogado("usuario");
           Login.fechar();
        } else {
            //tratar
        }
    } catch (Exception ex) {
      //tratar
    }
}

Finally, create a function in the Messagecontroller class to change the desired label. This function must be executed after the Controller class initialize method.

I hope I’ve helped.

  • The attributes can also be annotated with @FXML, and you can access them this way too as long as you put the right id in Scenebuilder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.