簡體   English   中英

Java FXML需要從另一個窗口重新加載comboBox

[英]Java FXML need to reload a comboBox from another window

(我使用的是Scene Builder)在我的控制器類中,有一個組合框,當我打開一個新窗口時,我用新項目填充了框內的列表,當我關閉該窗口時,我需要更改組合框,但是因為它不能是靜態的,我不知道一種方法。

第一個窗口的控制器類(相關部件)

public void initialize(URL location, ResourceBundle resources) {

    readCharacters();
    for (Character character : characterList) {
        System.out.println(character);
    }
    characterBox.setValue("Chars");
    characterList.sort(Comparator.comparing(Character::getPowerLevel).reversed());
    characterBox.setItems(FXCollections.observableArrayList(characterList));


}

因此,當我按下“新建”按鈕時,它將執行: 在此處輸入圖片說明

public void addNewWindow() throws IOException {

    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("newWindow.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        Stage stage = new Stage();
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

從上面的代碼開始 從上面的代碼開始

到目前為止,一切都很好,當我在下一個窗口中按“添加”按鈕時,將從Controller2類執行:

public void addNewCharacter() {

    if (addNameField.getText().equals("") || xField.getText().equals("") || pField.getText().equals("")) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Error");
        alert.setHeaderText(null);
        alert.setContentText("Please fill all fields");

        alert.showAndWait();
    } else {
        Controller.characterList.add(new Character(addNameField.getText(), Double.parseDouble(xField.getText()), Double.parseDouble(pField.getText()), specialButton.isSelected()));
        Controller.writeCharacters(); //this writes the characterList to a file for when i reopen the programm
    }
}

現在的問題是,完成后,原始窗口上的comboBox不會重新加載新條目,我需要重新打開程序以使用新條目進行更新。 因此,我該如何解決這個問題,顯然我無法將FXML字段設為靜態。 所以我想不通一種方法,將數據從Controller2發送到ComboBox到Controller。 除了在第一個窗口中創建重新加載按鈕外,我還需要其他解決方案。

由於將數據加載到ComboBox時是在初始化時發生的,因此,我發現必須重新加載應用程序才能看到新條目,對此我並不感到驚訝。 這是一個建議:

首先在第一個窗口的Controller上創建一個新方法。 使用適合更新ComboBox的輸入參數,使其成為公共訪問權限,例如:

public void addItem(Character c)
{
   // add your logic here to update the ComboBox collection of items
}

然后從第二個Controller中,使用FXMLLoader來獲取對第一個Controller的引用,如下所示:

FXMLLoader loader = new FXMLLoader(getClass().getResource("YourFirstWindow.fxml"));
FirstControllerClass firstController = loader.getController();

在動作事件處理程序代碼(必須是您的addNewCharacter()方法)中,在第一個Controller上調用new方法:

Character myNewCharacter = new Character(addNameField.getText(), Double.parseDouble(xField.getText()), Double.parseDouble(pField.getText()), specialButton.isSelected());
Controller.characterList.add(myNewCharacter);
Controller.writeCharacters();
firstController.addItem(myNewCharacter);

暫無
暫無

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

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