簡體   English   中英

JavaFX / FXML將ChoiceBox添加到根窗格

[英]JavaFX / FXML add ChoiceBox to root Pane

我已經開始用JavaFX編程。

我的問題是我不太了解場景構建器和“常規”代碼之間的聯系。

我有一個新的FXML文檔和這樣的代碼

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

我可以通過Scene Builder添加一些元素。 工作正常。 但是現在我想添加一個帶有某些值的ChoiceBox。 我可以通過Scene Builder添加一個空白的ChoiceBox。 但是沒有價值...

所以我找到一些代碼來創建帶有值的ChoiceBox

ChoiceBox cb = new ChoiceBox();

        cb.setItems(FXCollections.observableArrayList("Eins","Zwei","Drei","vier"));

        cb.setValue("Zwei");
        cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                System.out.println(cb.getValue());
            }

        });

它也很好。 但是如何將其添加到場景中? 我認為以下代碼行對我不起作用,因為我的根元素有一個FMXLLoader

root.getChildren().add(cb);

我認為只有在使用這樣的東西時,您才具有getChildren()方法

AnchorPane root = new AnchorPane();

但是然后我必須通過代碼對所有內容進行編碼,而無需通過Scene Builder進行任何編碼。 這樣對嗎? 還是有一種方法可以將“常規”代碼和場景構建器功能組合在一起?

謝謝

FXML只是創建對象結構的一種方式。 創建后如何處理這些對象完全取決於您。 如果從fxml創建場景圖,則可以使用Node來執行與使用Java代碼創建的對象相同的操作,包括將子代添加到Pane並設置ChoiceBox的項目...只需注入相關節點使用fx:id屬性連接到控制器,並通過使用FXMLLoader 實例加載fxml來使用控制器實例。

例:

message.fxml

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

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

<VBox fx:id="root" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxmltest.MessageController"> 
</VBox>
public class MessageController {

    @FXML
    private VBox root;

    public void addMessage(String message) {
        root.getChildren().add(new Label(message));
    }

}
FXMLLoader loader = new FXMLLoader(getClass().getResource("message.fxml"));
Parent root = loader.load();

MessageController controller = loader.getController();
controller.addMessage("Hello World");
controller.addMessage("42");

暫無
暫無

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

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