
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 将自动更新。
通过使用 ObservableValue(例如 StringProperty),我们可以轻松地在 JavaFX 应用程序中的控制器之间共享数据,并动态更新 UI。这种方法避免了创建控制器的新实例,确保了对原始 UI 元素的修改生效。记住,在实际开发中,需要注意封装性和内存管理。
立即学习“Java免费学习笔记(深入)”;
以上就是如何修改 Stage 所有者的 GUI 元素:JavaFX 教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号