簡體   English   中英

JavaFX - 將FXML包裝到Java類控制器

[英]JavaFX - Wrapping FXML to Java Class Controller

我有一個具有TreeView控件的FXML文件:

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="500.0" xmlns:fx="http://javafx.com/fxml" fx:controller="test.MyControllerClass">

<TreeView fx:id="locationTreeView" layoutX="12.0" layoutY="158.0" prefHeight="193.0" prefWidth="471.0" />

然后我的Java類控制器需要用這個TreeView包裝並動態添加TreeItem。 這就是問題,它沒有加載那些TreeItem。 這是我的控制器下面的測試代碼:

public class MyControllerClass extends Application {

    @FXML
    private TreeView<String> locationTreeView;

    @Override
    public void start(Stage stage) throws Exception {

        stage.initStyle(StageStyle.TRANSPARENT);
        stage.getIcons().add(new Image(getClass().getResourceAsStream("myIcon.png")));

        Parent root = FXMLLoader.load(getClass().getResource("myInterface.fxml"));

        Scene scene = new Scene(root);
        stage.setScene(scene);

        loadTreeItems();

        stage.show();
    }

    // Just a simple example that still doesn't works
    private void loadTreeItems() {

        try {
            TreeItem<String> root = new TreeItem<String>("Root Node");
            root.setExpanded(true);
            root.getChildren().addAll(
                new TreeItem<String>("Item 1"),
                new TreeItem<String>("Item 2"),
                new TreeItem<String>("Item 3")
            );

            locationTreeView = new TreeView<String>(root);

        } catch (Exception exc) {
            System.out.println("Error: " + exc.getMessage());
        }
    }

    public static void main(String[] args) {
         launch(args);
    }
}

任何想法為什么它不工作?

您的應用程序不起作用的原因有以下幾種:

  1. 您需要使Controller和Application分開。
  2. 您應該允許FXML系統注入TreeView實例而不是創建新實例(正如Aaron在他的回答中指出的那樣)。

您的應用程序當前結構化的方式將是:

  1. Java系統將在啟動時創建MyControllerClass的實例(並調用它的start方法)。
  2. 每次加載myInterface.fxml文件FXMLLoader都會創建另一個 MyControllerClass 實例
  3. FXMLLoader將創建一個新的TreeView實例,並在它創建的 MyControllerClass實例的locationTreeView成員上執行FXML注入。
  4. FXMLLoader將嘗試在新的MyControllerClass上調用initialize方法(其中沒有)。
  5. FXMLLoader 不會新的 MyControllerClass上調用start方法。
  6. 原始MyControllerClass上的原始start方法調用將繼續處理並創建另一個新的 TreeView實例,它將 MyControllerClass實例的locationTreeView成員設置為。

我更新了您的代碼以進行上面建議的修改,現在代碼可以正常工作。 更新的代碼可用

運行代碼的示例屏幕截圖如下: dynamictreeview

MyApplicationClass.java

import javafx.animation.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.*;
import javafx.util.Duration;

/** Sample application to demonstrate programming an FXML interface. */ 
public class MyApplicationClass extends Application {
  @Override public void start(final Stage stage) throws Exception {
    // load the scene fxml UI.
    // grabs the UI scenegraph view from the loader.
    // grabs the UI controller for the view from the loader.
    final FXMLLoader loader = new FXMLLoader(getClass().getResource("myInterface.fxml"));
    final Parent root = (Parent) loader.load();
    final MyControllerClass controller = loader.<MyControllerClass>getController();

    // continuously refresh the TreeItems.
    // demonstrates using controller methods to manipulate the controlled UI.
    final Timeline timeline = new Timeline(
      new KeyFrame(
        Duration.seconds(3), 
        new TreeLoadingEventHandler(controller)
      )
    );
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();

    // close the app if the user clicks on anywhere on the window.
    // just provides a simple way to kill the demo app.
    root.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
      @Override public void handle(MouseEvent t) {
        stage.hide();
      }
    });

    // initialize the stage.
    stage.setScene(new Scene(root));
    stage.initStyle(StageStyle.TRANSPARENT);
    stage.getIcons().add(new Image(getClass().getResourceAsStream("myIcon.png")));
    stage.show();
  }

  /** small helper class for handling tree loading events. */
  private class TreeLoadingEventHandler implements EventHandler<ActionEvent> {
    private MyControllerClass controller;
    private int idx = 0;

    TreeLoadingEventHandler(MyControllerClass controller) {
      this.controller = controller;
    }

    @Override public void handle(ActionEvent t) {
      controller.loadTreeItems("Loaded " + idx, "Loaded " + (idx + 1), "Loaded " + (idx + 2));
      idx += 3;
    }
  }

  // main method is only for legacy support - java 8 won't call it for a javafx application.
  public static void main(String[] args) { launch(args); }
}

MyControllerClass.java

import javafx.fxml.FXML;
import javafx.scene.control.*;

/** Sample controller class. */ 
public class MyControllerClass {
  // the FXML annotation tells the loader to inject this variable before invoking initialize.
  @FXML private TreeView<String> locationTreeView;

  // the initialize method is automatically invoked by the FXMLLoader - it's magic
  public void initialize() {
    loadTreeItems("initial 1", "initial 2", "initial 3");
  }  

  // loads some strings into the tree in the application UI.
  public void loadTreeItems(String... rootItems) {
    TreeItem<String> root = new TreeItem<String>("Root Node");
    root.setExpanded(true);
    for (String itemString: rootItems) {
      root.getChildren().add(new TreeItem<String>(itemString));
    }

    locationTreeView.setRoot(root);
  }
}

myInterface.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns:fx="http://javafx.com/fxml" fx:controller="test.MyControllerClass">
  <TreeView fx:id="locationTreeView" layoutX="0" layoutY="0" prefHeight="193.0" prefWidth="471.0" />
</AnchorPane>

在loadTreeItems()函數中,您將創建一個新的TreeView實例。 這將替換FXML文件中定義的並使用不屬於場景圖的新實例附加到場景的那個。

要將項添加到通過FXMLLoader創建的TreeView,您可以使用setRoot()函數。

private void loadTreeItems() {

    try {
        TreeItem<String> root = new TreeItem<String>("Root Node");
        root.setExpanded(true);
        root.getChildren().addAll(
            new TreeItem<String>("Item 1"),
            new TreeItem<String>("Item 2"),
            new TreeItem<String>("Item 3")
        );

        locationTreeView.setRoot(root);

    } catch (Exception exc) {
        System.out.println("Error: " + exc.getMessage());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM