简体   繁体   中英

want to change label text from another fxml controller class in javafx

I have two controller class Fxml1.java and Fxml2.java. In Fxml1.java I hava label Label l1, and in Fxml2.java I have text field t1. I have some text in text field t1 and I want to set this text to Label l1. i want to do some thing like below. Below is a just dummy code for understanding consider both class have separate fxml files. Here i receive NullPointerException.

 //class Fxml1
    public class Fxml1{

    public label l1;

    l1.setText("hello");

    }

    //class Fxml2
    public class Fxml2{
    public TextField t1;
    public Button b1;
    public Fxml1 ob;


    public void onButtonSubmit(ActionEvent event){
    ob  = new Fxml1();
    ob.l1.setText(t1.getText());
    }
     public void initialize(URL url, ResourceBundle rb){
    t1.setText("This is textfield text");
    }
    }

In your Fxml2 controller you are creating a new, completely separate instance of Fxml1 that is not linked to your fxml graph file, so it cannot update your required label since it has no access to it or any knowledge that it exists.

You should handle this through the use of events. A basic tutorial is can be found on Vogella's site .

Inject the event broker into both controllers:

@Inject IEventBroker broker;

In your Fxml2 controller you should post this string to the event broker when the text is updated:

public void onButtonSubmit(ActionEvent event) {
    broker.post("SomeSharedConstant", t1.getText());
}

In your Fxml1 controller, you should listen for this event and update your label when it is fired.

@Inject @Optional
public void  getEvent(@UIEventTopic("SomeSharedConstant") String text) {
    // text1 is a SWT Text field
    l1.setText(text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM