在Java FXML中,fx:root元素是FXML文件的根元素,它可以作为一个自定义控件的容器。fx:root元素可以包含子元素,这些子元素可以通过代码动态地添加到fx:root元素中。
要将子元素添加到fx:root元素的子元素中,可以通过以下步骤实现:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<VBox xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.Controller">
<Button text="子元素1" fx:id="button1" />
<Button text="子元素2" fx:id="button2" />
</VBox>
package com.example;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
public class Controller {
@FXML
private VBox root;
public void initialize() {
Button button3 = new Button("子元素3");
root.getChildren().add(button3);
}
}
package com.example;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Root.fxml"));
VBox root = loader.load();
Controller controller = loader.getController();
controller.initialize();
Scene scene = new Scene(root, 400, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
在上述代码中,通过FXMLLoader加载"Root.fxml"文件,并获取根元素VBox。然后,获取控制器Controller实例,并调用其initialize方法,在其中创建一个新的Button作为子元素,并将其添加到fx:root元素中。
这样,子元素就会被添加到fx:root元素的子元素中。在这个例子中,通过代码将"子元素3"添加到了fx:root元素中。
对于这个问题,腾讯云没有特定的产品或链接与之相关。
领取专属 10元无门槛券
手把手带您无忧上云