【问题标题】:How to get Stackpane from Main class in Controller class?如何从 Controller 类的 Main 类中获取 Stackpane?
【发布时间】:2015-07-19 14:04:23
【问题描述】:

为了熟悉场景构建器,我在场景构建器的堆栈窗格中添加了一个折线图和两个数字轴作为节点。 父节点会加载到mainApp.java中:

public class CsvCommander extends Application {    
    @Override
    public void start(Stage stage) throws Exception {        
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));           
        Scene scene = new Scene(root);        
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }   
}

现在,为了进一步的操作,我想在 FXMLDocument.fxml 中获取父级的堆栈窗格,但我不知道如何...

例如

StackPane 容器 = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml") 等。

如何在 Controller 通道中获取我的根节点或堆栈窗格?

【问题讨论】:

  • 如果 fxml 文件中的顶层父节点是您要获取的 Stackpane,则 Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")) 行的 root 变量是 Stackpane。您可以简单地向下转换为StackPane container = (StackPane) root;

标签: javafx controller parent fxml fxmlloader


【解决方案1】:

在FXML文件的根元素上放置一个fx:id,然后和其他元素一样注入到控制器中:

FXML 文件:

<!-- imports etc -->
<StackPane xmlns="..." fx:controller="com.example.MyControllerClass" fx:id="container">
    <!-- nodes etc -->
</StackPane>

控制器:

public class MyControllerClass {

    @FXML // will be initialized by FXMLLoader
    private StackPane container ;

    public void initialize() {
        // do something with container....
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-04
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多