
2. 修改 primarycontroller
在 PrimaryController 中,当加载 SecondaryController 时,将 Label 的 textProperty() 绑定到 SecondaryController 的 textProperty()。
package org.example;
import java.io.IOException;
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class PrimaryController {
@FXML
Label label;
public StringProperty text = new SimpleStringProperty();
@SuppressWarnings("unused")
public void login(ActionEvent event) throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("secondary.fxml"));
Parent root = loader.load();
SecondaryController secondaryController = loader.getController();
secondaryController.stage = new Stage();
secondaryController.stage.initModality(Modality.APPLICATION_MODAL);
secondaryController.stage.initOwner(App.stage);
label.textProperty().bind(secondaryController.textProperty()); // 绑定 textProperty
Scene scene = new Scene(root);
secondaryController.stage.setScene(scene);
secondaryController.stage.show();
}
public void displayMessage(String message){
label.setText(message);
}
}3. 运行应用程序
现在,当用户在弹出窗口的 TextField 中输入文本并提交时,所有者 Stage 上的 Label 将自动更新。
注意事项
- 避免公共访问: 在实际应用中,应尽量避免对类成员进行公共访问。可以使用 getter 和 setter 方法来控制对属性的访问。
- 更复杂的模型: 对于更复杂的应用程序,可以使用更复杂的模型,例如包含多个属性的 Java 类。
- 解绑: 如果不再需要绑定,请确保解除绑定,以避免内存泄漏。可以使用 label.textProperty().unbind(); 来解除绑定。
总结
通过使用 ObservableValue(例如 StringProperty),我们可以轻松地在 JavaFX 应用程序中的控制器之间共享数据,并动态更新 UI。这种方法避免了创建控制器的新实例,确保了对原始 UI 元素的修改生效。记住,在实际开发中,需要注意封装性和内存管理。
立即学习“Java免费学习笔记(深入)”;










