简体   繁体   English

要更改javafx中另一个fxml控制器类的标签文本

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

I have two controller class Fxml1.java and Fxml2.java. 我有两个控制器类Fxml1.java和Fxml2.java。 In Fxml1.java I hava label Label l1, and in Fxml2.java I have text field t1. 在Fxml1.java中,我具有标签l1,在Fxml2.java中,我具有文本字段t1。 I have some text in text field t1 and I want to set this text to Label l1. 我在文本字段t1中有一些文本,我想将此文本设置为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. 下面是一个简单的伪代码,用于理解认为两个类都有单独的fxml文件。 Here i receive NullPointerException. 在这里,我收到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. 在您的Fxml2控制器中,您正在创建一个新的,完全独立的Fxml1实例,该实例未链接到您的fxml图形文件,因此它无法更新所需的标签,因为它无权访问它或知道它的存在。

You should handle this through the use of events. 您应该通过使用事件来处理。 A basic tutorial is can be found on Vogella's site . Vogella的网站上可以找到基本的教程。

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: 在文本更新后,应在Fxml2控制器中将此字符串发布到事件代理:

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. 在Fxml1控制器中,您应该侦听此事件并在触发它时更新标签。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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