Javafx - 如何在加载后修改fxml文件中的组件 [英] Javafx - how to modify components in fxml file after loading it

查看:594
本文介绍了Javafx - 如何在加载后修改fxml文件中的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javafx的新手。我创建了一个简单的javafx fxml应用程序。我在我的fxml文件中定义了一个treeView。如下所示,

I am a novice to javafx. I created a simple javafx fxml application. I defined a treeView in my fxml file. It is as follows,

 <AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml/1"      xmlns="http://javafx.com/javafx/2.2" fx:controller="scenebuilderfirst.FXMLDocumentController">
   <children>
     <TreeView id="" fx:id="tree" layoutX="60.0" layoutY="14.0" prefHeight="172.0" prefWidth="200.0" />
   </children>
 </AnchorPane>

并按如下方式创建控制器类,

and created the controller class as follows,

 public class FXMLDocumentController implements Initializable {

     @FXML
     private TreeView<?> tree;   

     @Override
     public void initialize(URL url, ResourceBundle rb) {

     }    
 }

我的主要java文件如下,

my main java file is as follows,

 public class SceneBuilderFirst extends Application {

     @Override
     public void start(Stage stage) throws Exception {
         AnchorPane 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);
     }    
 }

现在我需要将树项添加到TreeView中运行程序。所以我想在我的contorller类的initialize()方法中写下以下代码的和平,

Now I need to add tree items to the TreeView while running the program. So I thought of writing the following peace of code inside the initialize() method of my contorller class,

    // creating root item for the tree
    TreeItem<String> rootItem = new TreeItem<>("root");
    rootItem.setExpanded(true);
    //creating childern for the tree
    TreeItem<String>item1= new TreeItem<>("content1");
    rootItem.getChildren().add(item1);
    TreeItem<String>item2= new TreeItem<>("content2");
    rootItem.getChildren().add(item2);

    //attaching root item to tree
    tree = new TreeView<>(rootItem);

但它不起作用。

我需要在运行程序时设置TreeItems。不是通过fxml文件。
所以我想我应该在我的主java文件中进行编码
我需要一种方法来通过FXMLLoader加载后访问我的TreeView 在我的主java文件中,所以我可以自己选择创建一个TreeView,并在运行程序时将其附加到此TreeView。请指导我。

I need to set the TreeItems while running the program. Not through the fxml file. So I think I should do the coding in my main java file I need a way to access my TreeView after loading it via FXMLLoader in my main java file so i can make a TreeView on my own choice and attach it to this TreeView while running the program. Please guide me.

推荐答案

要解决此问题,请更换

tree = new TreeView<>(rootItem);

with

tree.setRoot(rootItem);

有关原因的说明,请参阅此讨论

For an explanation of why, see this discussion.

您还必须修改<$ c $的声明c> TreeView :

@FXML
private TreeView<String> tree;  

这篇关于Javafx - 如何在加载后修改fxml文件中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆